-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathwebclient-core.js
More file actions
2318 lines (2057 loc) · 92.4 KB
/
webclient-core.js
File metadata and controls
2318 lines (2057 loc) · 92.4 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
/* global Triggers */
/**
* webclient-core.js
*
* Core infrastructure for the GoMud web client. Provides:
* - Client namespace (shared state accessible by window modules)
* - VirtualWindow class (lifecycle management for VWin panels)
* - VirtualWindows registry (GMCP handler dispatch)
* - WebSocket connection management
* - Terminal (xterm.js) setup
* - MSP audio (music + sound)
* - Volume slider UI
*
* Window modules call VirtualWindows.register(...) to add themselves.
* The HTML file calls Client.init() on page load.
*/
'use strict';
// ---------------------------------------------------------------------------
// injectStyles
//
// Appends a <style> block to <head>. Called by window modules at load time
// so each module owns and ships its own CSS alongside its JS.
// ---------------------------------------------------------------------------
function injectStyles(css) {
const style = document.createElement('style');
style.textContent = css;
document.head.appendChild(style);
}
// ---------------------------------------------------------------------------
// uiMenu
//
// Spawns a small context menu anchored near a click event.
// Dismisses on any outside click or when a command is chosen.
//
// Usage:
// uiMenu(event, [
// { label: 'look item', cmd: 'look longsword' },
// { label: 'remove item', cmd: 'remove longsword' },
// ]);
// ---------------------------------------------------------------------------
(function() {
let menuEl = null;
let offClick = null;
function dismiss() {
if (menuEl) {
menuEl.remove();
menuEl = null;
}
if (offClick) {
document.removeEventListener('mousedown', offClick, true);
offClick = null;
}
}
window.uiMenu = function uiMenu(event, items) {
dismiss();
menuEl = document.createElement('div');
menuEl.style.cssText = [
'position:fixed',
'z-index:2147483647',
'background:var(--t-bg-surface)',
'border:1px solid var(--t-btn-border)',
'border-radius:4px',
'box-shadow:0 4px 14px rgba(0,0,0,0.7)',
'padding:3px 0',
'min-width:120px',
'font-family:inherit',
'font-size:0.75em',
].join(';');
items.forEach(function(item) {
const entry = document.createElement('div');
entry.textContent = item.label;
entry.style.cssText = [
'padding:5px 12px',
'color:var(--t-text)',
'cursor:pointer',
'white-space:nowrap',
'letter-spacing:0.03em',
].join(';');
entry.addEventListener('mouseenter', function() {
entry.style.background = 'var(--t-accent-dim)';
entry.style.color = 'var(--t-text-white)';
});
entry.addEventListener('mouseleave', function() {
entry.style.background = '';
entry.style.color = 'var(--t-text)';
});
entry.addEventListener('mousedown', function(e) {
e.stopPropagation();
dismiss();
Client.SendInput(item.cmd);
});
menuEl.appendChild(entry);
});
// Position: prefer below-right of the click, flip if it would overflow
const vw = window.innerWidth;
const vh = window.innerHeight;
menuEl.style.left = '-9999px';
menuEl.style.top = '-9999px';
document.body.appendChild(menuEl);
const mw = menuEl.offsetWidth;
const mh = menuEl.offsetHeight;
let x = event.clientX;
let y = event.clientY + 4;
if (x + mw > vw - 8) { x = vw - mw - 8; }
if (y + mh > vh - 8) { y = event.clientY - mh - 4; }
menuEl.style.left = Math.max(8, x) + 'px';
menuEl.style.top = Math.max(8, y) + 'px';
offClick = function(e) {
if (menuEl && !menuEl.contains(e.target)) { dismiss(); }
};
document.addEventListener('mousedown', offClick, true);
};
}());
// ---------------------------------------------------------------------------
// DockSlot
//
// Manages one side's dock column (#dock-left or #dock-right).
// Handles:
// - adding / removing panels
// - showing / hiding the slot (zero-width when empty)
// - the slot-width drag handle
// - the per-panel vertical resize handles
// ---------------------------------------------------------------------------
class DockSlot {
constructor(side) {
this.side = side;
this.el = document.getElementById('dock-' + side);
this._panels = [];
if (!this.el) {
console.error('DockSlot: #dock-' + side + ' not found. Check that webclient-pure.html contains <div id="dock-' + side + '"> inside #main-container.');
return;
}
this._initSlotResize();
}
// Add a content element as a new panel with the given title.
// height (optional) sets the preferred panel height in px.
// onClose (optional) called when the panel's X button is clicked.
// onMoveTo (optional) called with (newSide, dropIdx) when dragged to the opposite slot.
// insertAt (optional) index at which to insert; appends if omitted or out of range.
// Returns the panel wrapper element.
addPanel(contentEl, title, onPopout, height, onClose, onMoveTo, insertAt) {
if (!this.el) { return null; }
const panel = document.createElement('div');
panel.className = 'dock-panel';
// Apply preferred height as a fixed flex-basis so the panel does not
// grow to fill the slot. The user can still drag the resize handle to
// redistribute space between panels.
if (height) {
panel.style.flex = '0 0 ' + height + 'px';
panel.style.flexBasis = height + 'px';
}
const titlebar = document.createElement('div');
titlebar.className = 'dock-panel-titlebar';
const titleSpan = document.createElement('span');
titleSpan.className = 'dock-panel-title';
titleSpan.textContent = title;
const popoutBtn = document.createElement('span');
popoutBtn.className = 'dock-panel-popout';
popoutBtn.title = 'Pop out';
popoutBtn.textContent = '⧉';
popoutBtn.addEventListener('click', onPopout);
titlebar.appendChild(titleSpan);
titlebar.appendChild(popoutBtn);
const content = document.createElement('div');
content.className = 'dock-panel-content';
content.appendChild(contentEl);
panel.appendChild(titlebar);
panel.appendChild(content);
// Wire up drag-to-reorder on the titlebar, with cross-slot transfer support
this._initPanelDrag(titlebar, panel, (newSide, dropIdx) => {
if (typeof onMoveTo === 'function') { onMoveTo(newSide, dropIdx); }
});
// Insert a vertical resize handle and the panel at the correct position.
// If insertAt is a valid index within the current panels, insert before
// that panel; otherwise append at the end.
const useInsert = (typeof insertAt === 'number' && insertAt >= 0 && insertAt < this._panels.length);
let resizeHandle = null;
if (useInsert) {
const refEntry = this._panels[insertAt];
// A resize handle goes between panels, so insert one before the new panel
// (which sits before refEntry).
resizeHandle = document.createElement('div');
resizeHandle.className = 'dock-panel-resize';
this.el.insertBefore(resizeHandle, refEntry.panel);
this._initPanelResize(resizeHandle);
this.el.insertBefore(panel, refEntry.panel);
this._panels.splice(insertAt, 0, { panel, contentEl, resizeHandle });
} else {
// Append at the end - only add a resize handle if there are existing panels.
if (this._panels.length > 0) {
resizeHandle = document.createElement('div');
resizeHandle.className = 'dock-panel-resize';
this.el.appendChild(resizeHandle);
this._initPanelResize(resizeHandle);
}
this.el.appendChild(panel);
this._panels.push({ panel, contentEl, resizeHandle });
}
this._setActive(true);
return panel;
}
// Remove a panel by its content element. Returns the content element.
removePanel(contentEl) {
if (!this.el) { return contentEl; }
const idx = this._panels.findIndex(p => p.contentEl === contentEl);
if (idx === -1) { return contentEl; }
const { panel, resizeHandle } = this._panels[idx];
// Remove the resize handle that was inserted before this panel,
// or the one after it if this is the first panel.
if (resizeHandle) {
resizeHandle.remove();
} else if (this._panels.length > 1) {
// This was the first panel; remove the handle that was after it
const next = this._panels[1];
if (next.resizeHandle) {
next.resizeHandle.remove();
next.resizeHandle = null;
}
}
// Move content back out before removing the panel
document.body.appendChild(contentEl);
panel.remove();
this._panels.splice(idx, 1);
if (this._panels.length === 0) {
this._setActive(false);
}
return contentEl;
}
hasPanel(contentEl) {
return this._panels.some(p => p.contentEl === contentEl);
}
_setActive(active) {
if (active) {
this.el.classList.add('has-panels');
} else {
this.el.classList.remove('has-panels');
}
// Defer until after the browser has completed its layout pass so
// fitAddon.fit() measures the terminal at its new settled dimensions.
requestAnimationFrame(() => window.dispatchEvent(new Event('resize')));
}
// Slot-width drag handle - inserted as a sibling of the slot in
// #main-container so it is never clipped by the slot's overflow:hidden.
// Hidden when the slot is empty, shown when it has panels.
_initSlotResize() {
if (!this.el) { return; }
const handle = document.createElement('div');
handle.className = 'dock-slot-resize dock-slot-resize-' + this.side;
// Insert adjacent to the slot inside #main-container
const container = this.el.parentNode;
if (this.side === 'right') {
container.insertBefore(handle, this.el);
} else {
this.el.insertAdjacentElement('afterend', handle);
}
// Keep visibility in sync with the slot's active state
const observer = new MutationObserver(() => {
handle.style.display = this.el.classList.contains('has-panels') ? '' : 'none';
});
observer.observe(this.el, { attributes: true, attributeFilter: ['class'] });
handle.style.display = 'none'; // hidden until first panel is added
let startX, startWidth, _rafPending = false;
const onMove = (e) => {
const dx = (e.clientX || e.touches[0].clientX) - startX;
const width = Math.max(80, startWidth + (this.side === 'right' ? -dx : dx));
this.el.style.setProperty('--dock-' + this.side + '-width', width + 'px');
this.el.style.width = width + 'px';
if (!_rafPending) {
_rafPending = true;
requestAnimationFrame(() => {
_rafPending = false;
window.dispatchEvent(new Event('resize'));
});
}
};
const onUp = () => {
handle.classList.remove('dragging');
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', onUp);
LayoutStore.saveDockWidths();
};
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
handle.classList.add('dragging');
startX = e.clientX;
startWidth = this.el.offsetWidth;
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
handle.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
startWidth = this.el.offsetWidth;
document.addEventListener('touchmove', onMove, { passive: false });
document.addEventListener('touchend', onUp);
}, { passive: true });
}
// Vertical resize handle between two stacked panels
_initPanelResize(handle) {
let startY, prevHeight, nextHeight, prevPanel, nextPanel;
const onMove = (e) => {
const dy = (e.clientY || e.touches[0].clientY) - startY;
const newPrev = Math.max(40, prevHeight + dy);
const newNext = Math.max(40, nextHeight - dy);
prevPanel.style.flexBasis = newPrev + 'px';
prevPanel.style.flex = '0 0 ' + newPrev + 'px';
nextPanel.style.flexBasis = newNext + 'px';
nextPanel.style.flex = '0 0 ' + newNext + 'px';
};
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', onUp);
// Save the docked height for both panels that were resized
[prevPanel, nextPanel].forEach(panelEl => {
if (!panelEl) { return; }
const entry = this._panels.find(p => p.panel === panelEl);
if (!entry) { return; }
const win = VirtualWindows.getWindows().find(w => w._contentEl === entry.contentEl);
if (win) { LayoutStore.saveWindow(win); }
});
};
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
startY = e.clientY;
prevPanel = handle.previousElementSibling;
nextPanel = handle.nextElementSibling;
prevHeight = prevPanel.offsetHeight;
nextHeight = nextPanel.offsetHeight;
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
handle.addEventListener('touchstart', (e) => {
startY = e.touches[0].clientY;
prevPanel = handle.previousElementSibling;
nextPanel = handle.nextElementSibling;
prevHeight = prevPanel.offsetHeight;
nextHeight = nextPanel.offsetHeight;
document.addEventListener('touchmove', onMove, { passive: false });
document.addEventListener('touchend', onUp);
}, { passive: true });
}
// Drag-to-reorder on a panel's titlebar.
// Shows a ghost label following the cursor and a drop indicator line
// between panels. On drop, reorders the panel in the DOM and _panels array,
// or calls onMoveTo(newSide, dropIdx) if dropped into the opposite slot.
_initPanelDrag(titlebar, panel, onMoveTo) {
titlebar.addEventListener('mousedown', (e) => {
// Ignore clicks on the action buttons
if (e.target.classList.contains('dock-panel-popout') ||
e.target.classList.contains('dock-panel-close')) {
return;
}
e.preventDefault();
const srcIdx = this._panels.findIndex(p => p.panel === panel);
if (srcIdx === -1) { return; }
const oppSide = this.side === 'left' ? 'right' : 'left';
const oppSlot = DockSlots[oppSide];
// Ghost label that follows the cursor
const ghost = document.createElement('div');
ghost.className = 'dock-drag-ghost';
ghost.textContent = titlebar.querySelector('.dock-panel-title').textContent;
document.body.appendChild(ghost);
// Two drop indicators - one per slot
const ownIndicator = document.createElement('div');
ownIndicator.className = 'dock-drop-indicator';
ownIndicator.style.display = 'none';
this.el.appendChild(ownIndicator);
let oppIndicator = null;
if (oppSlot && oppSlot.el) {
oppIndicator = document.createElement('div');
oppIndicator.className = 'dock-drop-indicator';
oppIndicator.style.display = 'none';
oppSlot.el.appendChild(oppIndicator);
}
panel.classList.add('dock-dragging');
let dropSide = this.side;
let dropIdx = srcIdx;
const _calcDropIdx = (slot, clientY) => {
const panels = slot._panels;
let idx = panels.length;
for (let i = 0; i < panels.length; i++) {
if (panels[i].panel === panel) { continue; }
const r = panels[i].panel.getBoundingClientRect();
if (clientY < r.top + r.height / 2) { idx = i; break; }
}
return idx;
};
const _showIndicator = (indicator, slot, idx) => {
if (!indicator || !slot.el) { return; }
const panels = slot._panels;
const slotRect = slot.el.getBoundingClientRect();
indicator.style.display = 'block';
if (panels.length === 0 || idx >= panels.length) {
const last = panels.length > 0 ? panels[panels.length - 1].panel : null;
indicator.style.top = last
? (last.getBoundingClientRect().bottom - slotRect.top + 2) + 'px'
: '4px';
} else {
const r = panels[idx].panel.getBoundingClientRect();
indicator.style.top = (r.top - slotRect.top - 2) + 'px';
}
};
const onMove = (e) => {
ghost.style.top = e.clientY + 'px';
const ownRect = this.el.getBoundingClientRect();
const oppRect = oppSlot && oppSlot.el ? oppSlot.el.getBoundingClientRect() : null;
// Determine which slot the cursor is over
const overOpp = oppRect &&
e.clientX >= oppRect.left && e.clientX <= oppRect.right &&
oppRect.width > 0;
if (overOpp) {
dropSide = oppSide;
dropIdx = _calcDropIdx(oppSlot, e.clientY);
ghost.style.left = oppRect.left + 'px';
ghost.style.width = oppRect.width + 'px';
ownIndicator.style.display = 'none';
_showIndicator(oppIndicator, oppSlot, dropIdx);
} else {
dropSide = this.side;
dropIdx = _calcDropIdx(this, e.clientY);
ghost.style.left = ownRect.left + 'px';
ghost.style.width = ownRect.width + 'px';
if (oppIndicator) { oppIndicator.style.display = 'none'; }
// Hide own indicator when drop would not change order
if (dropIdx === srcIdx || dropIdx === srcIdx + 1) {
ownIndicator.style.display = 'none';
} else {
_showIndicator(ownIndicator, this, dropIdx);
}
}
};
// Set initial ghost position
const initRect = this.el.getBoundingClientRect();
ghost.style.left = initRect.left + 'px';
ghost.style.width = initRect.width + 'px';
ghost.style.top = e.clientY + 'px';
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
ghost.remove();
ownIndicator.remove();
if (oppIndicator) { oppIndicator.remove(); }
panel.classList.remove('dock-dragging');
if (dropSide !== this.side) {
// Dropped into the opposite slot
if (typeof onMoveTo === 'function') {
onMoveTo(dropSide, dropIdx);
}
} else if (dropIdx !== srcIdx && dropIdx !== srcIdx + 1) {
// Reorder within own slot
this._movePanel(srcIdx, dropIdx);
}
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
// Reorder a panel from fromIdx to toIdx (insert-before semantics).
// Rebuilds the DOM order and the resize handles between panels.
_movePanel(fromIdx, toIdx) {
if (fromIdx === toIdx) { return; }
// Remove all resize handles from the DOM - we'll rebuild them
this._panels.forEach(p => {
if (p.resizeHandle) {
p.resizeHandle.remove();
p.resizeHandle = null;
}
});
// Reorder the _panels array
const moved = this._panels.splice(fromIdx, 1)[0];
const insertAt = toIdx > fromIdx ? toIdx - 1 : toIdx;
this._panels.splice(insertAt, 0, moved);
// Re-append panels to the slot in the new order
this._panels.forEach(p => this.el.appendChild(p.panel));
// Rebuild resize handles between adjacent panels
for (let i = 1; i < this._panels.length; i++) {
const handle = document.createElement('div');
handle.className = 'dock-panel-resize';
// Insert before the panel at index i
this.el.insertBefore(handle, this._panels[i].panel);
this._panels[i].resizeHandle = handle;
this._initPanelResize(handle);
}
// Notify the registry so the canonical order is updated
VirtualWindows.notifyReorder(this.side, this._panels.map(p => p.contentEl));
}
}
// Singleton slot instances, populated by Client.init() once the DOM is ready.
const DockSlots = {};
// ---------------------------------------------------------------------------
// LayoutStore
//
// Persists window layout to localStorage under the key 'windowLayout'.
// Saved state per window:
// enabled bool - whether the window is open
// docked bool - whether it is in a dock slot
// dockSide string - 'left' | 'right' (only when docked)
// dockedHeight number - panel height in px (only when docked)
// floatX number - VWin x position (only when floating)
// floatY number - VWin y position (only when floating)
// floatWidth number - VWin width (only when floating)
// floatHeight number - VWin height (only when floating)
// Plus top-level keys:
// dockWidths object - { left: number, right: number }
// ---------------------------------------------------------------------------
const LayoutStore = (() => {
const KEY = 'windowLayout';
function load() {
try {
const raw = localStorage.getItem(KEY);
return raw ? JSON.parse(raw) : {};
} catch (e) {
return {};
}
}
function save(data) {
try {
localStorage.setItem(KEY, JSON.stringify(data));
} catch (e) {
// localStorage unavailable - silently ignore
}
}
// Merge a partial update into the stored layout and persist.
function patch(updater) {
const data = load();
updater(data);
save(data);
}
// Save the current state of a single VirtualWindow.
function saveWindow(win) {
patch(data => {
if (!data.windows) { data.windows = {}; }
const entry = data.windows[win._id] || {};
entry.enabled = win.isOpen() || win._win === false ? win.isOpen() : true;
if (win._win === 'docked') {
entry.docked = true;
entry.dockSide = win._dockSide;
// Read current rendered panel height
const slot = DockSlots[win._dockSide];
if (slot) {
const pe = slot._panels.find(p => p.contentEl === win._contentEl);
if (pe) { entry.dockedHeight = Math.round(pe.panel.offsetHeight); }
}
} else if (win._win && win._win !== false) {
entry.docked = false;
entry.dockSide = win._dockSide;
entry.floatX = Math.round(win._win.x);
entry.floatY = Math.round(win._win.y);
entry.floatWidth = Math.round(win._win.width);
entry.floatHeight = Math.round(win._win.height);
} else {
// closed - preserve last known docked state
if (entry.docked === undefined) {
entry.docked = win._defaultDocked;
entry.dockSide = win._dockSide;
}
}
data.windows[win._id] = entry;
});
}
// Save dock slot widths.
function saveDockWidths() {
patch(data => {
data.dockWidths = {};
['left', 'right'].forEach(side => {
const slot = DockSlots[side];
if (slot && slot.el && slot.el.classList.contains('has-panels')) {
data.dockWidths[side] = slot.el.offsetWidth;
}
});
});
}
// Return saved state for a single window, or null.
function getWindow(id) {
const data = load();
return (data.windows && data.windows[id]) ? data.windows[id] : null;
}
function getDockWidths() {
const data = load();
return data.dockWidths || {};
}
function reset() {
localStorage.removeItem(KEY);
}
function clearWindow(id) {
patch(data => {
if (data.windows) { delete data.windows[id]; }
});
}
function saveDockOrder(order) {
patch(data => {
if (order) {
data.dockOrder = order;
} else {
delete data.dockOrder;
}
});
}
function getDockOrder() {
const data = load();
return data.dockOrder || null;
}
return { saveWindow, saveDockWidths, getWindow, getDockWidths, reset, clearWindow, saveDockOrder, getDockOrder };
})();
// ---------------------------------------------------------------------------
// VirtualWindow
//
// Wraps a VWin instance with a well-defined lifecycle and optional docking.
//
// States:
// undefined -> never opened
// 'docked' -> content is in a dock slot panel; no VWin exists
// VWin obj -> floating
// false -> user closed it from floating state; will not reopen
//
// Constructor options (passed as the second argument to VirtualWindow):
// factory() required Returns VWin opts object. Must append
// the content element to document.body.
// dock optional 'left' | 'right' - which slot to use.
// If omitted the window is float-only.
// defaultDocked optional boolean - start docked instead of floating.
// dockedHeight optional number (px) - preferred panel height when docked.
// Defaults to the height from the factory opts.
//
// Usage:
// const win = new VirtualWindow('id', {
// factory() { ... return { title, mount: el, ... }; },
// dock: 'right',
// defaultDocked: true,
// });
// win.open(); creates on first call, no-op if closed by user
// win.isOpen() true when floating or docked
// win.get() returns VWin instance, or null when docked/closed
// win.dock() move from floating -> docked
// win.undock() move from docked -> floating
// ---------------------------------------------------------------------------
class VirtualWindow {
constructor(id, options) {
this._id = id;
this._factory = options.factory;
this._dockSide = options.dock || null;
this._defaultDocked = options.defaultDocked || false;
this._dockedHeight = options.dockedHeight || null;
this._origDockSide = options.dock || null;
this._origDockedHeight = options.dockedHeight || null;
this._win = options.offOnLoad ? false : undefined;
this._contentEl = null;
this._vwinOpts = null;
}
// Open the window. On first call, honours defaultDocked and saved layout.
// Subsequent calls are no-ops unless the window is not yet open.
open() {
if (this._win !== undefined && this._win !== false) { return; } // already open (float or docked)
// Check saved layout for this window
const saved = LayoutStore.getWindow(this._id);
// If saved as disabled, mark closed and stop.
if (saved && saved.enabled === false) {
this._win = false;
return;
}
// offOnLoad windows stay closed unless the user has explicitly enabled them.
if (this._win === false && !(saved && saved.enabled === true)) {
return;
}
// Reset to undefined so the rest of open() treats this as a first open.
this._win = undefined;
// First open: run the factory to get opts + content element
const opts = this._factory();
if (!opts) { return; }
this._vwinOpts = opts;
this._contentEl = opts.mount;
// Apply saved float geometry if present
if (saved && saved.docked === false && saved.floatWidth) {
this._vwinOpts.x = saved.floatX;
this._vwinOpts.y = saved.floatY;
this._vwinOpts.width = saved.floatWidth;
this._vwinOpts.height = saved.floatHeight;
}
// Apply saved docked height
if (saved && saved.docked !== false && saved.dockedHeight) {
this._dockedHeight = saved.dockedHeight;
}
// Determine whether to dock or float
const shouldDock = saved
? (saved.docked !== false && !!this._dockSide)
: (this._dockSide && this._defaultDocked);
// If saved on a different dock side, update
if (saved && saved.dockSide && saved.docked !== false) {
this._dockSide = saved.dockSide;
}
if (shouldDock) {
this._dockNow();
} else {
this._floatNow();
}
}
isOpen() {
return this._win === 'docked' || (!!this._win && this._win !== false);
}
// Re-open a window that was previously closed by the user.
// Resets the closed state and opens as if for the first time.
reopen() {
if (this._win !== false) { return; }
this._win = undefined;
// Reset content so factory runs again on open()
this._contentEl = null;
this._vwinOpts = null;
// Clear any saved enabled:false so open() does not immediately re-close.
LayoutStore.clearWindow(this._id);
this.open();
LayoutStore.saveWindow(this);
}
// Returns the VWin instance when floating, null when docked or closed.
get() {
return (this._win && this._win !== false && this._win !== 'docked')
? this._win : null;
}
// Move from floating to docked. Safe to call when already docked.
dock() {
if (!this._dockSide) { return; }
if (this._win === 'docked') { return; }
if (!this._win || this._win === false) { return; }
// Destroy the VWin without triggering the user-close state
const wb = this._win;
wb.onclose = null;
wb.close();
this._win = undefined;
this._dockNow();
LayoutStore.saveWindow(this);
}
// Move from docked to floating. Safe to call when already floating.
undock() {
if (this._win !== 'docked') { return; }
const slot = DockSlots[this._dockSide];
// Measure the panel's current rendered dimensions before removing it,
// so the floating window matches what the user saw while docked.
// The titlebar height (~24px) is subtracted from the panel height to
// get the content-only height that VWin will use for its body.
let spawnY = null;
let spawnSize = null;
const panelEntry = slot._panels.find(p => p.contentEl === this._contentEl);
if (panelEntry) {
const rect = panelEntry.panel.getBoundingClientRect();
const titlebar = panelEntry.panel.querySelector('.dock-panel-titlebar');
const titleH = titlebar ? titlebar.offsetHeight : 24;
const margin = 10;
const spawnH = Math.round(rect.height);
const maxY = window.innerHeight - spawnH - margin;
spawnY = Math.min(Math.max(margin, Math.round(rect.top)), maxY);
spawnSize = { width: Math.round(rect.width), height: spawnH - titleH };
}
slot.removePanel(this._contentEl);
this._win = undefined;
this._floatNow(spawnY, spawnSize);
LayoutStore.saveWindow(this);
}
// -----------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------
_floatNow(spawnY, spawnSize) {
const opts = Object.assign({}, this._vwinOpts);
// If spawning from a docked position, use the panel's measured dimensions
// and place the window inset from the dock edge.
if (spawnY !== undefined && spawnY !== null) {
opts.y = spawnY;
opts.x = this._dockSide === 'right'
? window.innerWidth - (spawnSize ? spawnSize.width : (opts.width || 363)) - 50
: 50;
}
if (spawnSize) {
opts.width = spawnSize.width;
opts.height = spawnSize.height;
}
// Re-attach content to body if it was moved by the dock slot
if (this._contentEl && !document.body.contains(this._contentEl)) {
document.body.appendChild(this._contentEl);
}
opts.mount = this._contentEl;
// Inject close handler - sets state to false and removes the content
// element from the DOM so VWin's unmount() doesn't leave it visible
// as a bare element on document.body.
const userOnClose = opts.onclose;
opts.onclose = (force) => {
this._win = false;
if (this._contentEl && this._contentEl.parentNode) {
this._contentEl.parentNode.removeChild(this._contentEl);
}
LayoutStore.saveWindow(this);
if (typeof userOnClose === 'function') { return userOnClose(force); }
return false;
};
// Save position/size when the user moves or resizes the floating window.
const self = this;
const _saveThrottled = (() => {
let t = null;
return () => {
clearTimeout(t);
t = setTimeout(() => LayoutStore.saveWindow(self), 300);
};
})();
const existingOnMove = opts.onmove;
const existingOnResize = opts.onresize;
opts.onmove = function(x, y) {
if (existingOnMove) { existingOnMove.call(this, x, y); }
_saveThrottled();
};
opts.onresize = function(w, h) {
if (existingOnResize) { existingOnResize.call(this, w, h); }
_saveThrottled();
};
// Wrap oncreate to add the dock button.
// IMPORTANT: this._win must be set before oncreate fires because VWin
// calls oncreate synchronously inside its constructor, before the
// assignment `this._win = new VWin(opts)` completes. We use a
// placeholder object so addControl can be called safely, then replace
// it with the real VWin instance immediately after construction.
const existingOncreate = opts.oncreate;
if (this._dockSide) {
const self = this;
opts.oncreate = function(o) {
if (existingOncreate) { existingOncreate.call(this, o); }
this.addControl({
index: 0,
class: 'vw-dock-btn',
click: () => self.dock(),
});
};
} else if (existingOncreate) {
opts.oncreate = existingOncreate;
}
this._win = new VWin(opts);
}
_dockNow() {
const slot = DockSlots[this._dockSide];
const height = this._dockedHeight || (this._vwinOpts && this._vwinOpts.height) || null;
const insertAt = VirtualWindows.getDockInsertIndex(this);
slot.addPanel(
this._contentEl,
this._vwinOpts.title,
() => this.undock(),
height,
() => {
// User clicked X on the docked panel - same semantics as
// closing a floating window: remove content and deregister.
if (this._contentEl && this._contentEl.parentNode) {
this._contentEl.parentNode.removeChild(this._contentEl);
}
this._win = false;
},
(newSide) => {
// User dragged the panel to the opposite slot.
// Update the canonical order tables: remove from old side,
// append to new side (position will settle via notifyReorder
// once the panel is dropped and _movePanel fires, but we need
// the ID present in the new side's list for getDockInsertIndex).
VirtualWindows.notifySlotChange(this._id, this._dockSide, newSide);
slot.removePanel(this._contentEl);
this._dockSide = newSide;
this._win = undefined;
this._dockNow();
},
insertAt
);
this._win = 'docked';
LayoutStore.saveWindow(this);
}
}
// ---------------------------------------------------------------------------
// Default dock layout configuration.
//
// Defines which side each window docks to by default and the order windows
// appear within each dock (top-to-bottom). Edit this array to change the
// out-of-the-box layout. Modules not listed here fall back to their own
// constructor-declared dock side and are appended after configured windows.
// ---------------------------------------------------------------------------
const WINDOW_DOCK_DEFAULTS = [
{ id: 'Time & Date', side: 'left' },
{ id: 'Vitals', side: 'left' },
{ id: 'Character', side: 'left' },
{ id: 'Worth', side: 'left' },
{ id: 'Gear', side: 'left' },
{ id: 'Pet', side: 'left' },
{ id: 'Map', side: 'right' },
{ id: 'Online', side: 'right' },
{ id: 'KillStats', side: 'right' },
{ id: 'Party', side: 'right' },
{ id: 'Communications', side: 'right' },