-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.js
More file actions
825 lines (756 loc) · 30.5 KB
/
Copy patheditor.js
File metadata and controls
825 lines (756 loc) · 30.5 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
/** Set true after CodeMirror + history dock are initialized, so we do not render before panels exist. */
let _editorShellReady = false;
// ── Debug Console (runtime errors + console output) ──────────────────────
const _debugConsole = {
entries: [],
maxEntries: 400,
open: false,
hasNewErrors: false,
captureInstalled: false,
ui: {
btn: null,
panel: null,
output: null,
clearBtn: null,
closeBtn: null
},
originalConsole: null
};
function _dbgTime() {
// Short, stable time format for the console panel.
try {
return new Date().toISOString().slice(11, 19);
} catch (_) {
return '';
}
}
function _dbgArgToString(v) {
if (v instanceof Error) {
const head = v.name ? `${v.name}: ${v.message}` : v.message;
return v.stack ? `${head}\n${v.stack}` : String(head);
}
if (typeof v === 'string') return v;
if (typeof v === 'number' || typeof v === 'boolean' || v == null) return String(v);
try {
return JSON.stringify(v, null, 2);
} catch (_) {
try {
return String(v);
} catch (_) {
return '[Unprintable]';
}
}
}
function debugConsoleRender() {
const out = _debugConsole.ui.output;
if (!out) return;
out.textContent = _debugConsole.entries.join('\n');
out.scrollTop = out.scrollHeight;
}
function debugConsoleSetOpen(open) {
_debugConsole.open = !!open;
const { panel, btn } = _debugConsole.ui;
if (panel) {
panel.classList.toggle('open', _debugConsole.open);
panel.setAttribute('aria-hidden', String(!_debugConsole.open));
}
if (btn) {
btn.classList.toggle('has-new', _debugConsole.hasNewErrors && !_debugConsole.open);
}
if (_debugConsole.open) {
_debugConsole.hasNewErrors = false;
if (btn) btn.classList.toggle('has-new', false);
debugConsoleRender();
}
}
function debugConsoleAdd(level, args, stack) {
const time = _dbgTime();
const parts = (Array.isArray(args) ? args : [args]).filter((x) => x !== undefined);
const msg = parts.map(_dbgArgToString).filter(Boolean).join(' ');
const head = time ? `[${time}] ${level.toUpperCase()}: ${msg}` : `${level.toUpperCase()}: ${msg}`;
const full = stack ? `${head}\n${stack}` : head;
_debugConsole.entries.push(full);
if (_debugConsole.entries.length > _debugConsole.maxEntries) {
_debugConsole.entries.splice(0, _debugConsole.entries.length - _debugConsole.maxEntries);
}
if ((level === 'error' || level === 'warn') && !_debugConsole.open) {
_debugConsole.hasNewErrors = true;
if (_debugConsole.ui.btn) _debugConsole.ui.btn.classList.add('has-new');
}
if (_debugConsole.open) debugConsoleRender();
}
function initDebugConsole() {
const btn = document.getElementById('debugConsoleToggleBtn');
const panel = document.getElementById('debugConsolePanel');
const output = document.getElementById('debugConsoleOutput');
const clearBtn = document.getElementById('debugConsoleClearBtn');
const closeBtn = document.getElementById('debugConsoleCloseBtn');
if (!btn || !panel || !output) return;
_debugConsole.ui = { btn, panel, output, clearBtn, closeBtn };
btn.addEventListener('click', () => debugConsoleSetOpen(!_debugConsole.open));
clearBtn?.addEventListener('click', () => {
_debugConsole.entries = [];
_debugConsole.hasNewErrors = false;
btn.classList.toggle('has-new', false);
debugConsoleRender();
debugConsoleAdd('info', ['Console cleared']);
});
closeBtn?.addEventListener('click', () => debugConsoleSetOpen(false));
if (!_debugConsole.captureInstalled) {
_debugConsole.captureInstalled = true;
_debugConsole.originalConsole = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug
};
const orig = _debugConsole.originalConsole;
if (orig && typeof orig.error === 'function') {
console.error = (...args) => {
orig.error.apply(console, args);
debugConsoleAdd('error', args);
};
}
if (orig && typeof orig.warn === 'function') {
console.warn = (...args) => {
orig.warn.apply(console, args);
debugConsoleAdd('warn', args);
};
}
// Keep noise low when the console is closed.
const maybeCapture = (level) => (...args) => {
if (_debugConsole.open) debugConsoleAdd(level, args);
};
if (orig && typeof orig.log === 'function') console.log = (...args) => { orig.log.apply(console, args); if (_debugConsole.open) debugConsoleAdd('log', args); };
if (orig && typeof orig.info === 'function') console.info = (...args) => { orig.info.apply(console, args); if (_debugConsole.open) debugConsoleAdd('info', args); };
if (orig && typeof orig.debug === 'function') console.debug = (...args) => { orig.debug.apply(console, args); if (_debugConsole.open) debugConsoleAdd('debug', args); };
// If something throws before init runs, we still get `window.error` / `unhandledrejection`.
}
}
// If anything fails during startup/render, make it visible in the UI.
window.addEventListener('error', (e) => {
const msg = e && e.message ? e.message : e && e.error ? String(e.error) : 'Unknown error';
if (typeof setStatus === 'function') setStatus('Runtime error: ' + msg, 'error');
debugConsoleAdd('error', ['Runtime error: ' + msg], e && e.error && e.error.stack ? e.error.stack : undefined);
});
window.addEventListener('unhandledrejection', (e) => {
const msg =
e && e.reason && e.reason.message ? e.reason.message : e && e.reason ? String(e.reason) : 'Unknown rejection';
if (typeof setStatus === 'function') setStatus('Unhandled promise: ' + msg, 'error');
debugConsoleAdd('error', ['Unhandled promise: ' + msg], e && e.reason && e.reason.stack ? e.reason.stack : undefined);
});
initDebugConsole();
function markDirty() {
const d = docManager.activeDoc;
if (!d) return;
d.dirty = true;
docManager.dispatchEvent(new Event('tabs-changed'));
}
/**
* Apply a typed undo command (see VDataCommands) and record it on the stack.
* @param {object} cmd
* @param {string} [label]
*/
function withDocUndo(cmd, label) {
const d = docManager.activeDoc;
if (!d || !cmd || typeof VDataCommands === 'undefined') return;
VDataCommands.applyCommand(d, cmd);
pushUndoCommand({ cmd, label: label ?? 'Edit', time: Date.now() });
d.dirty = true;
docManager.dispatchEvent(new Event('tabs-changed'));
if (typeof patchPropertyTree === 'function') patchPropertyTree(cmd);
window.scheduleManualEditorSyncFromModel?.();
setStatus('Property edited', 'edited');
}
/**
* @param {object} [options]
* @param {boolean} [options.immediateManualSync] If true, flush debounce and push the full document into CodeMirror immediately (tab switches, first paint). Otherwise debounce + skip when editors panel is hidden.
* DevTools: on large files, Performance should show fewer long tasks in KV3/JSON serialize + CodeMirror replace after property edits (debounced path).
*/
function renderAll(options = {}) {
try {
const immediate = options.immediateManualSync === true;
// Defined in src/manual-editor.js; accessed via window for reliability.
if (immediate) {
window.flushSyncDebounce?.();
}
if (typeof buildPropertyTree === 'function') buildPropertyTree();
if (immediate) {
if (typeof syncManualEditor === 'function') syncManualEditor();
} else {
window.scheduleManualEditorSyncFromModel?.();
}
if (typeof updateStatusBar === 'function') updateStatusBar();
} catch (e) {
console.error('renderAll failed', e);
if (typeof setStatus === 'function') setStatus('Editor error: ' + (e && e.message ? e.message : String(e)), 'error');
}
}
function openWidgetConfigDialog() {
document.getElementById('widgetConfigDialog')?.remove();
const overlay = document.createElement('div');
overlay.id = 'widgetConfigDialog';
overlay.className = 'modal-overlay';
const dialog = document.createElement('div');
dialog.className = 'modal-dialog';
dialog.innerHTML = `
<div class="modal-header">
<span class="modal-title">Widget Config</span>
<button type="button" class="modal-close" id="wc-close">✕</button>
</div>
<div class="modal-body">
<div class="modal-section-label">User Rules <span class="modal-hint">(overwrite system)</span></div>
<div id="wc-user-rules"></div>
<div class="modal-row" style="margin-top:8px">
<input type="text" id="wc-new-match" class="prop-input" placeholder="key or /regex/" style="flex:1">
<select id="wc-new-type" class="prop-input" style="width:110px">
<option>string</option><option>int</option><option>float</option><option>bool</option>
<option>color</option><option>vec2</option><option>vec3</option><option>vec4</option>
<option>resource</option><option>soundevent</option>
</select>
<button type="button" class="btn btn-sm btn-accent" id="wc-add-btn">Add</button>
</div>
<div class="modal-section-label" style="margin-top:12px">System Rules <span class="modal-hint">(read-only)</span></div>
<div id="wc-sys-rules" class="wc-readonly-list"></div>
</div>
`;
overlay.appendChild(dialog);
document.body.appendChild(overlay);
function refreshUserRules() {
const container = document.getElementById('wc-user-rules');
container.innerHTML = '';
VDataSettings.getUserRules().forEach((rule) => {
const row = document.createElement('div');
row.className = 'modal-row';
row.innerHTML = `<span class="wc-match"></span><span class="wc-type prop-type-badge">${rule.type}</span>`;
row.querySelector('.wc-match').textContent = rule.match;
const del = document.createElement('button');
del.type = 'button';
del.className = 'btn btn-sm btn-danger';
del.textContent = '✕';
del.addEventListener('click', () => {
VDataSettings.removeUserRule(rule.match);
refreshUserRules();
renderAll();
});
row.appendChild(del);
container.appendChild(row);
});
}
const sysContainer = document.getElementById('wc-sys-rules');
VDataSettings.SYSTEM_CONFIG.rules.forEach((rule) => {
const row = document.createElement('div');
row.className = 'modal-row wc-sys-row';
row.innerHTML = `<span class="wc-match"></span><span class="wc-type prop-type-badge">${rule.type}</span>`;
row.querySelector('.wc-match').textContent = rule.match;
sysContainer.appendChild(row);
});
refreshUserRules();
document.getElementById('wc-add-btn').addEventListener('click', () => {
const match = document.getElementById('wc-new-match').value.trim();
const wtype = document.getElementById('wc-new-type').value;
if (!match) return;
VDataSettings.setUserRule(match, wtype);
document.getElementById('wc-new-match').value = '';
refreshUserRules();
renderAll();
});
document.getElementById('wc-close').addEventListener('click', () => overlay.remove());
overlay.addEventListener('click', (e) => {
if (e.target === overlay) overlay.remove();
});
}
/** Rebuild mode dropdown (Auto + Generic + registered modes, including runtime `schema:…` entries). */
function rebuildEditorModeSelect() {
const sel = document.getElementById('editorModeSelect');
if (!sel || !window.VDataEditorModes) return;
const prev = sel.value;
sel.innerHTML = '';
const auto = document.createElement('option');
auto.value = 'auto';
auto.textContent = 'Document Context';
sel.appendChild(auto);
const generic = window.VDataEditorModes.getModeById('generic');
if (generic) {
const opt = document.createElement('option');
opt.value = 'generic';
opt.textContent = generic.label || 'Generic';
sel.appendChild(opt);
}
window.VDataEditorModes.listModes().forEach((m) => {
const opt = document.createElement('option');
opt.value = m.id;
opt.textContent = m.label;
sel.appendChild(opt);
});
const ok = Array.from(sel.options).some((o) => o.value === prev);
sel.value = ok ? prev : 'auto';
syncEditorModeSelect();
if (typeof refreshPropertyBrowserContextList === 'function') refreshPropertyBrowserContextList();
if (typeof refreshPropertyBrowserPropertyList === 'function') refreshPropertyBrowserPropertyList();
}
function initEditorModeSelect() {
const sel = document.getElementById('editorModeSelect');
if (!sel || sel.dataset.bound || !window.VDataEditorModes) return;
sel.dataset.bound = '1';
rebuildEditorModeSelect();
sel.addEventListener('change', () => {
syncEditorModeSelect();
renderAll();
});
syncEditorModeSelect();
}
function initPropertySchemaGameSelect() {
const sel = document.getElementById('propSchemaGameSelect');
if (!sel || sel.dataset.bound) return;
sel.dataset.bound = '1';
const runtime = window.VDataSchemaRuntime;
const current = runtime && typeof runtime.getSchemaGame === 'function' ? runtime.getSchemaGame() : 'cs2';
sel.value = current === 'dota2' || current === 'deadlock' || current === 'cs2' ? current : 'cs2';
sel.addEventListener('change', async () => {
const game = sel.value;
if (!runtime || typeof runtime.setSchemaGame !== 'function') return;
const ok = runtime.setSchemaGame(game);
if (!ok) return;
try {
if (typeof setSchemaProgress === 'function') setSchemaProgress(true, 0, 'Switching schema game…');
if (typeof VDataSuggestions?.initSchemas === 'function') {
await VDataSuggestions.initSchemas(window.reportSchemaDownloadProgress);
}
if (typeof setStatus === 'function') setStatus('Schema game: ' + game, 'info');
renderAll();
} catch (e) {
if (typeof setStatus === 'function') setStatus('Schema switch failed: ' + (e && e.message ? e.message : e), 'error');
} finally {
if (typeof setSchemaProgress === 'function') setSchemaProgress(false);
}
});
}
window.addEventListener('vdata-schema-modes-updated', () => {
rebuildEditorModeSelect();
});
async function loadRecentFiles() {
if (!window.electronAPI?.getRecentFiles) return;
try {
const list = await window.electronAPI.getRecentFiles();
renderRecentMenu(list);
} catch (_) {
renderRecentMenu([]);
}
}
function renderRecentMenu(list) {
const container = document.getElementById('menuRecentFiles');
if (!container) return;
container.innerHTML = '';
if (!list || !list.length) {
const empty = document.createElement('div');
empty.className = 'menu-dropdown-item';
empty.style.opacity = '0.45';
empty.textContent = 'No recent files';
container.appendChild(empty);
return;
}
list.forEach((p) => {
const item = document.createElement('div');
item.className = 'menu-dropdown-item';
item.textContent = pathBasename(p);
item.title = p;
item.addEventListener('click', (e) => {
e.stopPropagation();
openFileByPath(p);
document.querySelectorAll('.menu-dropdown').forEach((d) => d.classList.remove('open'));
});
container.appendChild(item);
});
const sep = document.createElement('div');
sep.className = 'menu-sep';
const clear = document.createElement('div');
clear.className = 'menu-dropdown-item';
clear.textContent = 'Clear Recent';
clear.addEventListener('click', (e) => {
e.stopPropagation();
window.electronAPI.clearRecentFiles().then(() => renderRecentMenu([]));
document.querySelectorAll('.menu-dropdown').forEach((d) => d.classList.remove('open'));
});
container.appendChild(sep);
container.appendChild(clear);
}
function initRecentFilesMenu() {
const wrap = document.querySelector('.menu-submenu-wrap');
const sub = document.getElementById('menuRecentFiles');
if (!wrap || !sub) return;
wrap.addEventListener('mouseenter', () => {
if (window.electronAPI?.getRecentFiles) loadRecentFiles();
});
if (window.electronAPI?.onRecentFilesUpdated) {
window.electronAPI.onRecentFilesUpdated((list) => renderRecentMenu(list));
}
loadRecentFiles();
}
function initPropDockToolbar() {
const c = document.getElementById('tb-collapse-all');
const x = document.getElementById('tb-expand-all');
c?.addEventListener('click', () => setAllCollapsed(true));
x?.addEventListener('click', () => setAllCollapsed(false));
}
// ── Docking ─────────────────────────────────────────────────────────────
const dockPanelMap = {
'property-browser': document.getElementById('propertyBrowserPanel'),
properties: document.getElementById('propsPanel'),
editors: document.getElementById('editorsPanel')
};
const dockFloatingState = {};
function undockPanel(id) {
const panel = dockPanelMap[id];
if (!panel || panel.classList.contains('dock-floating')) return;
const rect = panel.getBoundingClientRect();
const container = document.getElementById('dockContainer');
dockFloatingState[id] = {
nextSibling: panel.nextElementSibling,
parent: panel.parentElement,
width: panel.style.width,
flex: panel.style.flex,
minWidth: panel.style.minWidth
};
panel.classList.add('dock-floating');
panel.style.left = Math.min(rect.left, window.innerWidth - 400) + 'px';
panel.style.top = Math.min(rect.top, window.innerHeight - 300) + 'px';
panel.style.width = Math.max(rect.width, 300) + 'px';
panel.style.height = Math.max(rect.height, 250) + 'px';
panel.style.flex = 'none';
panel.style.minWidth = '0';
container.appendChild(panel);
const btn = panel.querySelector('.dock-handle-actions button[onclick*="undockPanel"]');
if (btn) {
btn.onclick = () => redockPanel(id);
btn.title = 'Dock';
btn.innerHTML = ICONS.dock;
}
makeDraggable(panel, panel.querySelector('.dock-handle'));
makeResizable(panel);
}
function redockPanel(id) {
const panel = dockPanelMap[id];
if (!panel || !panel.classList.contains('dock-floating')) return;
const state = dockFloatingState[id];
panel.classList.remove('dock-floating');
panel.style.left = '';
panel.style.top = '';
panel.style.height = '';
panel.style.position = '';
if (state) {
panel.style.width = state.width;
panel.style.flex = state.flex;
panel.style.minWidth = state.minWidth;
if (state.nextSibling && state.parent.contains(state.nextSibling)) {
state.parent.insertBefore(panel, state.nextSibling);
} else {
state.parent.appendChild(panel);
}
}
delete dockFloatingState[id];
const btn = panel.querySelector('.dock-handle-actions button[title="Dock"]');
if (btn) {
btn.onclick = () => undockPanel(id);
btn.title = 'Undock';
btn.innerHTML = ICONS.undock;
}
panel.querySelectorAll('.floating-resize-handle').forEach((h) => h.remove());
}
function makeDraggable(panel, handle) {
let startX, startY, startLeft, startTop;
function onMouseDown(e) {
if (e.target.tagName === 'BUTTON' || e.target.tagName === 'INPUT') return;
e.preventDefault();
startX = e.clientX;
startY = e.clientY;
startLeft = parseInt(panel.style.left, 10) || 0;
startTop = parseInt(panel.style.top, 10) || 0;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
function onMouseMove(e) {
panel.style.left = startLeft + e.clientX - startX + 'px';
panel.style.top = startTop + e.clientY - startY + 'px';
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
handle.addEventListener('mousedown', onMouseDown);
}
function makeResizable(panel) {
const handle = document.createElement('div');
handle.className = 'floating-resize-handle';
handle.style.cssText =
'position:absolute;bottom:0;right:0;width:14px;height:14px;cursor:nwse-resize;z-index:101';
panel.appendChild(handle);
let startX, startY, startW, startH;
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
startX = e.clientX;
startY = e.clientY;
startW = panel.offsetWidth;
startH = panel.offsetHeight;
function onMove(e2) {
panel.style.width = Math.max(250, startW + e2.clientX - startX) + 'px';
panel.style.height = Math.max(200, startH + e2.clientY - startY) + 'px';
}
function onUp() {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
}
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
document.querySelectorAll('.dock-resize-h').forEach((handle) => {
let startX, leftPanel, rightPanel, startLeftW, startRightW;
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
handle.classList.add('active');
leftPanel = handle.previousElementSibling;
rightPanel = handle.nextElementSibling;
if (!leftPanel || !rightPanel) return;
startX = e.clientX;
startLeftW = leftPanel.offsetWidth;
startRightW = rightPanel.offsetWidth;
function onMove(e2) {
const dx = e2.clientX - startX;
const newLeft = Math.max(180, startLeftW + dx);
const newRight = Math.max(200, startRightW - dx);
leftPanel.style.width = newLeft + 'px';
leftPanel.style.flex = `${newLeft} 1 ${newLeft}px`;
rightPanel.style.width = newRight + 'px';
rightPanel.style.flex = `${newRight} 1 ${newRight}px`;
}
function onUp() {
handle.classList.remove('active');
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
}
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
});
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
if (e.key === 'n') {
e.preventDefault();
newDocument();
return;
}
if (e.key === 's') {
e.preventDefault();
if (e.shiftKey) saveFileAs();
else saveFile();
return;
}
if (e.key === 'z' || e.key === 'Z') {
e.preventDefault();
if (e.shiftKey) redo();
else undo();
return;
}
if (e.key === 'y' || e.key === 'Y') {
e.preventDefault();
redo();
return;
}
}
});
function reportSchemaDownloadProgress(msg, pct) {
if (typeof setSchemaProgress === 'function') {
setSchemaProgress(true, pct != null && pct !== '' ? Number(pct) : 0, msg || '');
}
if (typeof setStatus === 'function') {
setStatus(pct != null && pct !== '' ? msg + ' (' + pct + '%)' : msg, 'info');
}
}
window.reportSchemaDownloadProgress = reportSchemaDownloadProgress;
function formatSchemaAgeMs(ms) {
if (ms == null || typeof ms !== 'number') return '—';
const s = Math.floor(ms / 1000);
if (s < 60) return s + ' s';
const m = Math.floor(s / 60);
if (m < 60) return m + ' min';
const h = Math.floor(m / 60);
if (h < 72) return h + ' h';
return Math.floor(h / 24) + ' d';
}
function refreshSchemaDialogStatus(overlay) {
const R = window.VDataSchemaRuntime;
if (!R || typeof R.getSchemaCacheStatus !== 'function' || !overlay) return;
const st = R.getSchemaCacheStatus();
const ttlDays = (st.ttlMs / 86400000).toFixed(1);
const ageEl = overlay.querySelector('#scd-age');
const staleEl = overlay.querySelector('#scd-stale');
const fetchedEl = overlay.querySelector('#scd-fetched');
const countEl = overlay.querySelector('#scd-count');
const ttlEl = overlay.querySelector('#scd-ttl');
if (ageEl) ageEl.textContent = st.hasData && st.ageMs != null ? formatSchemaAgeMs(st.ageMs) + ' ago' : '—';
if (staleEl) staleEl.textContent = !st.hasData ? 'No cache' : st.isStale ? 'Update available' : 'Up to date';
if (fetchedEl) {
fetchedEl.textContent = st.hasData && st.fetchedAt ? new Date(st.fetchedAt).toLocaleString() : '—';
}
if (countEl) countEl.textContent = String(st.schemaKeyCount);
if (ttlEl) ttlEl.textContent = ttlDays + ' days';
}
function showSchemaCacheAdvancedDialog() {
document.getElementById('schemaCacheDialog')?.remove();
const R = window.VDataSchemaRuntime;
const S = window.VDataSuggestions;
if (!R || !S) {
if (typeof setStatus === 'function') setStatus('Schema runtime not available', 'error');
return;
}
const overlay = document.createElement('div');
overlay.id = 'schemaCacheDialog';
overlay.className = 'modal-overlay';
overlay.innerHTML = `
<div class="modal-dialog" style="width:440px">
<div class="modal-header">
<span class="modal-title">Manage schemas</span>
<button type="button" class="modal-close" id="scd-close">✕</button>
</div>
<div class="modal-body">
<p style="margin:0 0 12px;font-size:12px;color:var(--text-muted);line-height:1.45">
Check schema cache status and update when needed.
</p>
<table style="width:100%;font-size:12px;border-collapse:collapse">
<tr><td style="padding:4px 10px 4px 0;color:var(--text-muted);vertical-align:top">Cache age</td><td id="scd-age">—</td></tr>
<tr><td style="padding:4px 10px 4px 0;color:var(--text-muted)">Status</td><td id="scd-stale">—</td></tr>
<tr><td style="padding:4px 10px 4px 0;color:var(--text-muted)">Last updated</td><td id="scd-fetched">—</td></tr>
<tr><td style="padding:4px 10px 4px 0;color:var(--text-muted)">Schema entries</td><td id="scd-count">0</td></tr>
<tr><td style="padding:4px 10px 4px 0;color:var(--text-muted)">Refresh window</td><td id="scd-ttl">—</td></tr>
</table>
<div class="modal-row" style="margin-top:16px;flex-wrap:wrap;gap:8px;justify-content:flex-start">
<button type="button" class="btn btn-sm" id="scd-update-if-stale">Update if needed</button>
<button type="button" class="btn btn-sm btn-accent" id="scd-force">Download fresh copy</button>
</div>
</div>
</div>`;
document.body.appendChild(overlay);
refreshSchemaDialogStatus(overlay);
overlay.querySelector('#scd-close')?.addEventListener('click', () => overlay.remove());
overlay.addEventListener('click', (e) => {
if (e.target === overlay) overlay.remove();
});
overlay.querySelector('#scd-update-if-stale')?.addEventListener('click', async () => {
const st = R.getSchemaCacheStatus();
if (st.hasData && !st.isStale) {
if (typeof setStatus === 'function') setStatus('Schemas are already up to date.', 'info');
refreshSchemaDialogStatus(overlay);
return;
}
try {
await S.refreshSchemasAdvanced(window.reportSchemaDownloadProgress, { forceRefresh: false });
} finally {
if (typeof setSchemaProgress === 'function') setSchemaProgress(false);
refreshSchemaDialogStatus(overlay);
if (typeof setStatus === 'function') setStatus('Schemas updated', 'info');
}
});
overlay.querySelector('#scd-force')?.addEventListener('click', async () => {
try {
await S.refreshSchemasAdvanced(window.reportSchemaDownloadProgress, { forceRefresh: true });
} finally {
if (typeof setSchemaProgress === 'function') setSchemaProgress(false);
refreshSchemaDialogStatus(overlay);
if (typeof setStatus === 'function') setStatus('Downloaded fresh schemas', 'info');
}
});
}
window.showSchemaCacheAdvancedDialog = showSchemaCacheAdvancedDialog;
if (typeof window !== 'undefined' && window.StartupProfiler) {
window.StartupProfiler.startPhase('editor-theme-init', { description: 'Initialize app theme' });
}
if (typeof initAppTheme === 'function') initAppTheme();
if (typeof window !== 'undefined' && window.StartupProfiler) window.StartupProfiler.endPhase();
if (typeof window !== 'undefined' && window.StartupProfiler) {
window.StartupProfiler.startPhase('editor-menu-tab-init', { description: 'Initialize menu and tab bar' });
}
initMenuBar();
if (window.electronAPI?.getPlatform) {
void window.electronAPI.getPlatform().then((p) => {
if (p !== 'win32') {
const el = document.getElementById('menuHelpWin11Freeze');
if (el) el.style.display = 'none';
}
});
}
initTabBar();
if (typeof window !== 'undefined' && window.StartupProfiler) window.StartupProfiler.endPhase();
if (typeof initSchemaProgressUI === 'function') {
initSchemaProgressUI(['cs2', 'dota2', 'deadlock']);
}
if (window.VDataPropTreePerf && typeof window.VDataPropTreePerf.initPropTreeLazy === 'function') {
window.VDataPropTreePerf.initPropTreeLazy('propTreeRoot');
}
// Register active-changed BEFORE newDoc() so the first event is caught.
docManager.addEventListener('active-changed', () => {
// Tab switches must rebuild the property tree; incremental DOM updates assume structure matches activeDoc.
if (typeof markPropTreeStructureDirty === 'function') markPropTreeStructureDirty();
const d = docManager.activeDoc;
if (d) {
document.title = 'VDataEditor - ' + d.fileName;
syncEditorModeSelect();
}
if (typeof refreshHistoryDock === 'function') refreshHistoryDock();
if (_editorShellReady) {
const deferCm = d && d.deferInitialManualEditorSync;
if (deferCm) delete d.deferInitialManualEditorSync;
renderAll({ immediateManualSync: !deferCm });
}
});
if (typeof window !== 'undefined' && window.StartupProfiler) {
window.StartupProfiler.startPhase('editor-ui-init', { description: 'Initialize UI panels and property tree' });
}
docManager.newDoc(); // fires active-changed → renderAll() syncs manual editor when shell is ready
initPropTreeSearch();
if (typeof initPropTreeColumnResize === 'function') initPropTreeColumnResize();
if (typeof initPropTreePanelContextMenu === 'function') initPropTreePanelContextMenu();
if (typeof initPropTreeSelectionAndSuggestionDnD === 'function') initPropTreeSelectionAndSuggestionDnD();
initHistoryDock();
initEditorModeSelect();
initPropertySchemaGameSelect();
initRecentFilesMenu();
initPropDockToolbar();
_editorShellReady = true;
if (typeof window !== 'undefined' && window.StartupProfiler) {
window.StartupProfiler.endPhase();
window.StartupProfiler.startPhase('editor-render', { description: 'First render and finalization' });
}
renderAll({ immediateManualSync: true });
if (typeof window !== 'undefined' && window.StartupProfiler) {
window.StartupProfiler.endPhase();
}
if (typeof runEditorDeferredInit === 'function') {
runEditorDeferredInit({
initPropertyBrowser: function () {
if (typeof initPropertyBrowser === 'function') initPropertyBrowser();
},
initSchemas: function () {
if (typeof VDataSuggestions?.initSchemas !== 'function') return;
VDataSuggestions.initSchemas(window.reportSchemaDownloadProgress)
.catch(function () {
/* offline / fetch errors logged in initSchemas */
})
.finally(function () {
if (typeof setSchemaProgress === 'function') setSchemaProgress(false);
});
}
});
}
if (window.electronAPI?.getVersion) {
window.electronAPI.getVersion().then((v) => {
const lbl = document.getElementById('versionLabel');
if (lbl) lbl.textContent = `VDataEditor v${v}`;
});
}
if (window.electronAPI) {
window.electronAPI.onOpenFile((filePath) => {
openFileByPath(filePath).catch(() => {});
});
}