-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop-context-menu.js
More file actions
844 lines (746 loc) · 39.5 KB
/
desktop-context-menu.js
File metadata and controls
844 lines (746 loc) · 39.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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
// desktop-context-menu.js
(function(window) {
'use strict';
const DESKTOP_ICON_POSITIONS_KEY = 'desktopIconPositions_win9x_style_v2'; // Consistent key
const DESKTOP_BACKGROUND_COLOR_KEY = 'desktopBgColor_win9x';
const DESKTOP_BACKGROUND_IMAGE_KEY = 'desktopBgImage_win9x';
const DESKTOP_ICON_ARRANGE_PREFS_KEY = 'desktopIconArrangePrefs_win9x_v1';
const DEFAULT_GRID_SIZE_X = 85;
const DEFAULT_GRID_SIZE_Y = 87;
let desktopElement;
let contextMenuElement = null;
let displayPropertiesDialog = null;
let currentBgColor = '#008080';
let currentBgImage = '';
let currentArrangeMode = 'name';
let autoArrangeEnabled = false;
// Long-press detection variables
let longPressTimer = null;
const LONG_PRESS_DURATION = 500; // milliseconds
let pointerDownClientX = 0;
let pointerDownClientY = 0;
const MAX_MOVE_THRESHOLD = 10; // pixels to allow movement before cancelling long press
function makeDialogDraggable(dialogElement, titleBarElement) {
let offsetX, offsetY, isDragging = false;
titleBarElement.addEventListener('pointerdown', (e) => {
if (e.target.closest('button')) return;
isDragging = true;
const dialogRect = dialogElement.getBoundingClientRect();
offsetX = e.clientX - dialogRect.left;
offsetY = e.clientY - dialogRect.top;
titleBarElement.style.cursor = 'grabbing';
const currentZ = parseInt(window.getComputedStyle(dialogElement).zIndex) || 15000;
dialogElement.style.zIndex = currentZ + 1;
document.body.classList.add('no-select');
});
document.addEventListener('pointermove', (e) => {
if (!isDragging) return;
let newX = e.clientX - offsetX;
let newY = e.clientY - offsetY;
const vpWidth = desktopElement.clientWidth;
const vpHeight = desktopElement.clientHeight;
const dialogWidth = dialogElement.offsetWidth;
const dialogHeight = dialogElement.offsetHeight;
newX = Math.max(0, Math.min(newX, vpWidth - dialogWidth));
newY = Math.max(0, Math.min(newY, vpHeight - dialogHeight));
dialogElement.style.left = `${newX}px`;
dialogElement.style.top = `${newY}px`;
});
document.addEventListener('pointerup', () => {
if (isDragging) {
isDragging = false;
titleBarElement.style.cursor = 'grab';
document.body.classList.remove('no-select');
}
});
}
function openDisplayProperties() {
hideContextMenu();
if (displayPropertiesDialog && desktopElement.contains(displayPropertiesDialog)) {
const currentZ = parseInt(window.getComputedStyle(displayPropertiesDialog).zIndex) || 15000;
displayPropertiesDialog.style.zIndex = currentZ + 1;
displayPropertiesDialog.querySelector('input, button')?.focus();
return;
}
displayPropertiesDialog = document.createElement('div');
displayPropertiesDialog.className = 'display-properties-dialog';
const initialLeft = Math.max(0, (desktopElement.clientWidth - 380) / 2);
const initialTop = Math.max(0, (desktopElement.clientHeight - 320) / 3);
displayPropertiesDialog.style.left = `${initialLeft}px`;
displayPropertiesDialog.style.top = `${initialTop}px`;
displayPropertiesDialog.style.zIndex = '15001';
displayPropertiesDialog.innerHTML = `
<div class="display-properties-dialog-titlebar">
<span class="display-properties-dialog-title">Display Properties</span>
<div class="display-properties-dialog-controls">
<button class="dialog-close-btn" title="Close">r</button>
</div>
</div>
<div class="display-properties-dialog-content">
<div class="display-properties-tabs">
<div class="display-properties-tab active" data-tab="background">Background</div>
</div>
<div class="display-properties-tab-content active" data-tab-content="background">
<fieldset style="margin-bottom:10px;">
<legend>Wallpaper</legend>
<div class="display-properties-preview" id="dpPreview"></div>
<label for="dpBgImageFile" style="display:block; margin:5px 0;">Select an image (max 1MB):</label>
<input type="file" id="dpBgImageFile" accept="image/jpeg, image/png, image/gif, image/webp" style="margin-bottom:5px; width: calc(100% - 8px);">
<button id="dpClearImageBtn" class="win95-button" style="padding: 2px 8px; min-width: auto;">Remove Image</button>
</fieldset>
<fieldset>
<legend>Color</legend>
<label for="dpBgColor" style="display:block; margin:5px 0;">Select background color:</label>
<input type="color" id="dpBgColor" value="${currentBgColor}" style="width: 60px; height: 25px;">
</fieldset>
</div>
<div class="display-properties-buttons">
<button id="dpOkBtn" class="win95-button">OK</button>
<button id="dpCancelBtn" class="win95-button">Cancel</button>
<button id="dpApplyBtn" class="win95-button">Apply</button>
</div>
</div>
`;
desktopElement.appendChild(displayPropertiesDialog);
const titleBar = displayPropertiesDialog.querySelector('.display-properties-dialog-titlebar');
makeDialogDraggable(displayPropertiesDialog, titleBar);
const closeBtn = displayPropertiesDialog.querySelector('.dialog-close-btn');
const okBtn = displayPropertiesDialog.querySelector('#dpOkBtn');
const cancelBtn = displayPropertiesDialog.querySelector('#dpCancelBtn');
const applyBtn = displayPropertiesDialog.querySelector('#dpApplyBtn');
const colorInput = displayPropertiesDialog.querySelector('#dpBgColor');
const imageInput = displayPropertiesDialog.querySelector('#dpBgImageFile');
const clearImageBtn = displayPropertiesDialog.querySelector('#dpClearImageBtn');
const previewEl = displayPropertiesDialog.querySelector('#dpPreview');
if (closeBtn.style.fontFamily.toLowerCase().includes('marlett')) {
closeBtn.style.fontSize = '10px';
}
function updatePreview() {
previewEl.style.backgroundColor = colorInput.value;
const file = imageInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => { previewEl.style.backgroundImage = `url(${e.target.result})`; };
reader.readAsDataURL(file);
} else if (imageInput.value === "") {
previewEl.style.backgroundImage = 'none';
}
else if (currentBgImage && !file) {
previewEl.style.backgroundImage = `url(${currentBgImage})`;
}
}
previewEl.style.backgroundColor = currentBgColor;
if (currentBgImage) previewEl.style.backgroundImage = `url(${currentBgImage})`;
else previewEl.style.backgroundImage = 'none';
colorInput.value = currentBgColor;
colorInput.addEventListener('input', updatePreview);
imageInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file && file.size > 1 * 1024 * 1024) {
alert("Image is too large! Please select an image under 1MB.");
imageInput.value = "";
}
updatePreview();
});
clearImageBtn.addEventListener('click', () => {
imageInput.value = "";
updatePreview();
});
function applySettings() {
const newBgColor = colorInput.value;
desktopElement.style.backgroundColor = newBgColor;
localStorage.setItem(DESKTOP_BACKGROUND_COLOR_KEY, newBgColor);
currentBgColor = newBgColor;
if (typeof window.updateThemeForDesktopBackground === 'function') {
window.updateThemeForDesktopBackground(newBgColor);
}
const file = imageInput.files[0];
if (file && file.size <= 1 * 1024 * 1024) {
const reader = new FileReader();
reader.onload = (e) => {
currentBgImage = e.target.result;
desktopElement.style.backgroundImage = `url(${currentBgImage})`;
desktopElement.style.backgroundSize = 'cover';
desktopElement.style.backgroundPosition = 'center';
localStorage.setItem(DESKTOP_BACKGROUND_IMAGE_KEY, currentBgImage);
};
reader.readAsDataURL(file);
} else if (imageInput.value === "" && previewEl.style.backgroundImage === 'none') {
currentBgImage = '';
desktopElement.style.backgroundImage = 'none';
localStorage.removeItem(DESKTOP_BACKGROUND_IMAGE_KEY);
}
}
applyBtn.addEventListener('click', applySettings);
okBtn.addEventListener('click', () => {
applySettings();
displayPropertiesDialog.remove();
displayPropertiesDialog = null;
});
function closeDialogWithoutSaving() {
displayPropertiesDialog.remove();
displayPropertiesDialog = null;
}
cancelBtn.addEventListener('click', closeDialogWithoutSaving);
closeBtn.addEventListener('click', closeDialogWithoutSaving);
displayPropertiesDialog.querySelector('input, button')?.focus();
}
function loadDesktopPreferences() {
currentBgColor = localStorage.getItem(DESKTOP_BACKGROUND_COLOR_KEY) || '#008080';
currentBgImage = localStorage.getItem(DESKTOP_BACKGROUND_IMAGE_KEY) || '';
desktopElement.style.backgroundColor = currentBgColor;
if (currentBgImage) {
desktopElement.style.backgroundImage = `url(${currentBgImage})`;
desktopElement.style.backgroundSize = 'cover';
desktopElement.style.backgroundPosition = 'center';
} else {
desktopElement.style.backgroundImage = 'none';
}
if (typeof window.updateThemeForDesktopBackground === 'function') {
window.updateThemeForDesktopBackground(currentBgColor);
}
}
function createContextMenu(menuModel = null) {
if (contextMenuElement && desktopElement.contains(contextMenuElement)) {
contextMenuElement.remove();
}
contextMenuElement = buildMenuTree(Array.isArray(menuModel) ? menuModel : getDesktopMenuModel(), false);
desktopElement.appendChild(contextMenuElement);
hideContextMenu(); // Create hidden by default
}
function loadArrangePreferences() {
try {
const raw = localStorage.getItem(DESKTOP_ICON_ARRANGE_PREFS_KEY);
if (!raw) return;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return;
const mode = typeof parsed.mode === 'string' ? parsed.mode.trim().toLowerCase() : '';
if (mode === 'name' || mode === 'type' || mode === 'size' || mode === 'date') {
currentArrangeMode = mode;
}
autoArrangeEnabled = parsed.autoArrange === true;
} catch (error) {
console.error('ContextMenu: failed to load arrange prefs:', error);
}
}
function saveArrangePreferences() {
try {
localStorage.setItem(DESKTOP_ICON_ARRANGE_PREFS_KEY, JSON.stringify({
mode: currentArrangeMode,
autoArrange: autoArrangeEnabled,
}));
} catch (error) {
console.error('ContextMenu: failed to save arrange prefs:', error);
}
}
function getVisibleDesktopIcons() {
if (window.Win9xDesktopUtils && typeof window.Win9xDesktopUtils.getAllVisibleDesktopIcons === 'function') {
return window.Win9xDesktopUtils.getAllVisibleDesktopIcons();
}
return Array.from(desktopElement.querySelectorAll('.desktop-icon')).filter((icon) => icon.style.display !== 'none');
}
function getIconMetadata(icon) {
const labelEl = icon.querySelector('span');
const name = (labelEl ? labelEl.textContent : '').trim().toLowerCase();
const itemId = icon.dataset ? icon.dataset.desktopItemId : '';
const itemType = icon.dataset ? icon.dataset.itemType : '';
const appId = icon.dataset ? icon.dataset.appId : '';
const desktopItem = (itemId && window.Win9xDesktopItems && typeof window.Win9xDesktopItems.getItemById === 'function')
? window.Win9xDesktopItems.getItemById(itemId)
: null;
const typeKey = (itemType || (desktopItem && desktopItem.type) || (appId ? 'application' : '')).toLowerCase();
const typeOrderMap = {
application: 0,
folder: 1,
shortcut: 2,
textdocument: 3,
bitmapimage: 4,
wavesound: 5,
};
const typeOrder = Object.prototype.hasOwnProperty.call(typeOrderMap, typeKey) ? typeOrderMap[typeKey] : 99;
const sortDate = (desktopItem && typeof desktopItem.createdAt === 'number') ? desktopItem.createdAt : 0;
const sortSize = (desktopItem && typeof desktopItem.size === 'number')
? desktopItem.size
: ((icon.offsetWidth || 0) * (icon.offsetHeight || 0));
return { name, typeOrder, sortDate, sortSize };
}
function arrangeDesktopIcons(mode) {
if (!desktopElement) return;
if (mode) currentArrangeMode = mode;
const icons = getVisibleDesktopIcons();
if (icons.length === 0) return;
icons.sort((a, b) => {
const metaA = getIconMetadata(a);
const metaB = getIconMetadata(b);
if (currentArrangeMode === 'type') {
if (metaA.typeOrder !== metaB.typeOrder) return metaA.typeOrder - metaB.typeOrder;
return metaA.name.localeCompare(metaB.name);
}
if (currentArrangeMode === 'size') {
if (metaA.sortSize !== metaB.sortSize) return metaB.sortSize - metaA.sortSize;
return metaA.name.localeCompare(metaB.name);
}
if (currentArrangeMode === 'date') {
if (metaA.sortDate !== metaB.sortDate) return metaB.sortDate - metaA.sortDate;
return metaA.name.localeCompare(metaB.name);
}
return metaA.name.localeCompare(metaB.name);
});
const metrics = (window.SnapToGrid && typeof window.SnapToGrid.getDesktopIconAreaMetrics === 'function')
? window.SnapToGrid.getDesktopIconAreaMetrics(desktopElement)
: {
iconAreaOffsetX: 10,
iconAreaOffsetY: 10,
contentWidthForGrid: desktopElement.clientWidth - 20,
contentHeightForGrid: desktopElement.clientHeight - 20,
maxCols: Math.max(1, Math.floor((desktopElement.clientWidth - 20) / DEFAULT_GRID_SIZE_X)),
maxRows: Math.max(1, Math.floor((desktopElement.clientHeight - 20) / DEFAULT_GRID_SIZE_Y)),
};
const maxRows = Math.max(1, metrics.maxRows || 1);
const maxCols = Math.max(1, metrics.maxCols || 1);
const limit = maxRows * maxCols;
if (icons.length > limit) {
console.warn(`ContextMenu: arranging ${icons.length} icons into ${limit} slots; some overlap may occur.`);
}
const storedPositions = (() => {
try {
const raw = localStorage.getItem(DESKTOP_ICON_POSITIONS_KEY);
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
})();
icons.forEach((icon, index) => {
const col = Math.floor(index / maxRows) % maxCols;
const row = index % maxRows;
const left = metrics.iconAreaOffsetX + (col * DEFAULT_GRID_SIZE_X);
const top = metrics.iconAreaOffsetY + (row * DEFAULT_GRID_SIZE_Y);
icon.style.position = 'absolute';
icon.style.margin = '0';
icon.style.left = `${left}px`;
icon.style.top = `${top}px`;
icon.classList.add('is-positioned');
const storageKey = icon.dataset && icon.dataset.desktopItemId
? `item:${icon.dataset.desktopItemId}`
: (icon.dataset ? icon.dataset.appId : null);
if (storageKey) {
storedPositions[storageKey] = { x: left, y: top };
}
});
try {
localStorage.setItem(DESKTOP_ICON_POSITIONS_KEY, JSON.stringify(storedPositions));
} catch (error) {
console.error('ContextMenu: failed to persist arranged positions:', error);
}
saveArrangePreferences();
}
function arrangeByName() {
arrangeDesktopIcons('name');
}
function arrangeByType() {
arrangeDesktopIcons('type');
}
function arrangeBySize() {
arrangeDesktopIcons('size');
}
function arrangeByDate() {
arrangeDesktopIcons('date');
}
function toggleAutoArrange() {
autoArrangeEnabled = !autoArrangeEnabled;
if (autoArrangeEnabled) {
arrangeDesktopIcons(currentArrangeMode);
} else {
saveArrangePreferences();
}
}
function getDesktopMenuModel() {
const newItems = getNewMenuItems();
return [
{
text: "<u>A</u>ctive Desktop",
disabled: true,
submenu: [
{ text: "View as Web Page", disabled: true },
{ text: "Customize my Desktop...", disabled: true },
]
},
{
text: "<u>A</u>rrange Icons",
submenu: [
{ text: "by <u>N</u>ame", action: arrangeByName },
{ text: "by <u>T</u>ype", action: arrangeByType },
{ text: "by <u>S</u>ize", action: arrangeBySize },
{ text: "by <u>D</u>ate", action: arrangeByDate },
{ separator: true },
{ text: "<u>A</u>uto Arrange", action: toggleAutoArrange },
{ text: "<u>L</u>ine Up Icons", action: lineUpIcons },
]
},
{ text: "<u>L</u>ine Up Icons", action: lineUpIcons },
{ separator: true },
{ text: "<u>R</u>efresh", action: () => window.location.reload() },
{ separator: true },
{ text: "<u>P</u>aste", disabled: true },
{ text: "Pas<u>t</u>e Shortcut", disabled: true },
{ separator: true },
{ text: "<u>N</u>ew", submenu: newItems },
{ separator: true },
{ text: "P<u>r</u>operties", action: openDisplayProperties },
];
}
function getNewMenuItems() {
if (window.Win9xDesktopItems && typeof window.Win9xDesktopItems.getNewMenuEntries === 'function') {
return window.Win9xDesktopItems.getNewMenuEntries().map((entry) => ({
text: entry.label,
icon: entry.icon,
disabled: entry.enabled === false,
action: typeof entry.action === 'function' ? entry.action : null,
}));
}
return [
{ text: "Folder", icon: './directory_closed_cool-0.png', disabled: true },
{ text: "Shortcut", icon: './html-0.png', disabled: true },
{ text: "Text Document", icon: './notepad-0.png', disabled: true },
];
}
function lineUpIcons() {
if (window.Win9xDesktopUtils && typeof Win9xDesktopUtils.snapSelectedIconsToGrid === 'function') {
Win9xDesktopUtils.snapSelectedIconsToGrid();
} else {
alert("Line Up Icons feature not available.");
}
}
function buildMenuTree(menuItems, isSubmenu) {
const menu = document.createElement('div');
menu.className = isSubmenu ? 'desktop-context-submenu' : 'desktop-context-menu';
menuItems.forEach((itemDef, index) => {
if (itemDef.separator) {
if (index > 0 && menu.lastChild && !menu.lastChild.classList.contains('desktop-context-menu-separator')) {
const sep = document.createElement('div');
sep.className = 'desktop-context-menu-separator';
menu.appendChild(sep);
}
return;
}
const menuItem = document.createElement('div');
menuItem.className = 'desktop-context-menu-item';
if (itemDef.disabled) {
menuItem.classList.add('disabled');
}
if (itemDef.icon) {
const iconEl = document.createElement('img');
iconEl.className = 'desktop-context-menu-item-icon';
iconEl.src = itemDef.icon;
iconEl.alt = '';
menuItem.appendChild(iconEl);
}
const labelEl = document.createElement('span');
labelEl.className = 'desktop-context-menu-item-label';
labelEl.innerHTML = itemDef.text || '';
menuItem.appendChild(labelEl);
if (Array.isArray(itemDef.submenu) && itemDef.submenu.length > 0) {
menuItem.classList.add('has-submenu');
const arrowEl = document.createElement('span');
arrowEl.className = 'desktop-context-menu-submenu-arrow';
arrowEl.innerHTML = '<svg width="8" height="10" viewBox="0 0 8 10" fill="currentColor"><path d="M0 0l8 5-8 5z"/></svg>';
menuItem.appendChild(arrowEl);
menuItem.appendChild(buildMenuTree(itemDef.submenu, true));
}
if (!itemDef.disabled && typeof itemDef.action === 'function') {
menuItem.addEventListener('click', (e) => {
e.stopPropagation();
itemDef.action();
if (itemDef.action !== openDisplayProperties) {
hideContextMenu();
}
});
}
menu.appendChild(menuItem);
});
return menu;
}
function positionSubmenuForViewport(menuItem) {
if (!menuItem || !desktopElement || !contextMenuElement) return;
const submenu = menuItem.querySelector(':scope > .desktop-context-submenu');
if (!submenu) return;
const wasDisplayed = submenu.style.display;
submenu.style.display = 'block';
submenu.style.visibility = 'hidden';
const desktopRect = desktopElement.getBoundingClientRect();
const itemRect = menuItem.getBoundingClientRect();
const submenuRect = submenu.getBoundingClientRect();
const viewportPadding = 5;
const wouldOverflowRight = (itemRect.right + submenuRect.width + viewportPadding) > desktopRect.right;
const wouldOverflowLeft = (itemRect.left - submenuRect.width - viewportPadding) < desktopRect.left;
const openLeft = wouldOverflowRight && !wouldOverflowLeft;
menuItem.classList.toggle('submenu-left', openLeft);
let topOffset = -3;
const projectedBottom = itemRect.top + topOffset + submenuRect.height;
const maxBottom = desktopRect.bottom - viewportPadding;
if (projectedBottom > maxBottom) {
topOffset -= (projectedBottom - maxBottom);
}
const minTop = desktopRect.top + viewportPadding;
if (itemRect.top + topOffset < minTop) {
topOffset = minTop - itemRect.top;
}
submenu.style.top = `${Math.round(topOffset)}px`;
submenu.style.visibility = '';
submenu.style.display = wasDisplayed || '';
}
function wireSubmenuEdgeHandlers(rootMenu) {
if (!rootMenu) return;
rootMenu.querySelectorAll('.desktop-context-menu-item.has-submenu').forEach((item) => {
if (item.dataset.edgeWired === '1') return;
item.dataset.edgeWired = '1';
item.addEventListener('mouseenter', () => {
positionSubmenuForViewport(item);
});
});
}
function positionAndShowContextMenu(event) {
const desktopRect = desktopElement.getBoundingClientRect();
let x = event.clientX - desktopRect.left;
let y = event.clientY - desktopRect.top;
contextMenuElement.style.display = 'block';
const menuRect = contextMenuElement.getBoundingClientRect();
const padding = 5;
const overflowsRight = x + menuRect.width + padding > desktopElement.clientWidth;
if (overflowsRight) x = desktopElement.clientWidth - menuRect.width - padding;
if (y + menuRect.height + padding > desktopElement.clientHeight) y = desktopElement.clientHeight - menuRect.height - padding;
x = Math.max(padding, x);
y = Math.max(padding, y);
contextMenuElement.classList.toggle('opens-from-right-edge', overflowsRight);
contextMenuElement.style.left = `${x}px`;
contextMenuElement.style.top = `${y}px`;
contextMenuElement.style.zIndex = '20000';
wireSubmenuEdgeHandlers(contextMenuElement);
// These listeners are for hiding the menu if a click happens *outside*
// The pointerdown at the end of the file handles general clicks outside.
// The 'click' and 'contextmenu' listeners here are specific to *after* the menu is shown.
setTimeout(() => {
document.addEventListener('click', handleClickOutsideContextMenu, { once: true, capture: true });
// Add contextmenu listener to prevent native menu if right-click happens while our menu is up
document.addEventListener('contextmenu', handleRightClickOutsideContextMenu, { once: true, capture: true });
}, 0);
}
function showContextMenu(event, targetIcon = null) {
// If targetIcon is not specified (i.e., contextmenu on desktop background or long press on desktop):
// then check if the event.target is on a window/dialog/menu itself and prevent if so.
if (!targetIcon) {
if (event.target.closest('.window:not(.desktop-icon .window)') || // General window (not an icon's pseudo-window)
event.target.closest('.display-properties-dialog') || // Display properties dialog
event.target.closest('.desktop-context-menu')) { // The context menu itself
return; // Do not show menu on these elements if it's a general desktop context action
}
}
// If targetIcon *is* specified, it means an icon handler explicitly called this,
// so we assume it's valid to show the menu for that icon.
event.preventDefault(); // Prevent native context menu
event.stopPropagation(); // Stop event from bubbling further
// Always ensure desktop menu model is active when showing the desktop context menu.
createContextMenu(getDesktopMenuModel());
if (targetIcon && targetIcon.classList.contains('desktop-icon')) {
if (window.Win9xDesktopUtils && typeof Win9xDesktopUtils.clearSelection === 'function' && !event.ctrlKey && !event.metaKey) {
Win9xDesktopUtils.clearSelection();
}
targetIcon.classList.add('selected');
if (window.Win9xDesktopUtils && window.Win9xDesktopUtils.selectedIcons) {
window.Win9xDesktopUtils.selectedIcons.add(targetIcon);
}
}
positionAndShowContextMenu(event);
}
function showCustomContextMenu(event, menuModel) {
if (!event || !Array.isArray(menuModel)) return;
if (event.target && event.target.closest && event.target.closest('.desktop-context-menu')) {
return;
}
event.preventDefault();
event.stopPropagation();
createContextMenu(menuModel);
positionAndShowContextMenu(event);
}
function hideContextMenu() {
if (contextMenuElement) contextMenuElement.style.display = 'none';
// Clean up listeners added by showContextMenu
document.removeEventListener('click', handleClickOutsideContextMenu, { capture: true });
document.removeEventListener('contextmenu', handleRightClickOutsideContextMenu, { capture: true });
}
function handleClickOutsideContextMenu(event) {
if (contextMenuElement && contextMenuElement.style.display === 'block') {
if (!contextMenuElement.contains(event.target)) {
hideContextMenu();
} else { // Click was inside the menu, re-arm listeners
document.addEventListener('click', handleClickOutsideContextMenu, { once: true, capture: true });
document.addEventListener('contextmenu', handleRightClickOutsideContextMenu, { once: true, capture: true });
}
}
}
function handleRightClickOutsideContextMenu(event) {
if (contextMenuElement && contextMenuElement.style.display === 'block') {
if (!contextMenuElement.contains(event.target)) { // Click outside
hideContextMenu();
// Potentially show a new context menu at the new location if it's on the desktop
// but the main 'contextmenu' listener on desktopElement should handle this.
} else { // Click inside our menu
event.preventDefault(); // Prevent native context menu if right-clicking inside our custom menu
}
}
}
function _arrangeIcons() {
try { localStorage.removeItem(DESKTOP_ICON_POSITIONS_KEY); }
catch (e) { console.error("Error clearing icon positions:", e); }
const allIconsOnDesktop = Array.from(desktopElement.querySelectorAll('.desktop-icon'));
allIconsOnDesktop.forEach(icon => {
icon.style.position = ''; icon.style.left = ''; icon.style.top = '';
icon.style.margin = '';
icon.classList.remove('is-positioned', 'selected');
});
if (window.Win9xDesktopUtils && typeof Win9xDesktopUtils.clearSelection === 'function') {
Win9xDesktopUtils.clearSelection();
}
if (window.Win9xDesktopUtils && typeof Win9xDesktopUtils.forceRelayoutAllIcons === 'function') {
Win9xDesktopUtils.forceRelayoutAllIcons();
} else {
console.warn("forceRelayoutAllIcons not found. Icons may not reposition correctly after Arrange.");
}
hideContextMenu();
}
// --- Long-press Helper Functions ---
function handleDesktopPointerDownForLongPress(e) {
// Only for primary button (touch, or left mouse button if testing)
if (e.pointerType === 'mouse' && e.button !== 0) return;
// IMPORTANT: Do NOT trigger desktop long-press if the target is an icon,
// a window, a dialog, or the context menu itself.
// Icon long-press should be handled by the icon's own event listeners,
// which would then call `DesktopContextMenu.show(e, iconElement)`.
if (e.target.closest('.desktop-icon') ||
e.target.closest('.window:not(.desktop-icon .window)') || // General window
e.target.closest('.display-properties-dialog') ||
e.target.closest('.desktop-context-menu')) {
clearLongPressTimer(); // Just in case
return;
}
pointerDownClientX = e.clientX;
pointerDownClientY = e.clientY;
if (longPressTimer) clearTimeout(longPressTimer); // Clear any existing timer
longPressTimer = setTimeout(() => {
longPressTimer = null; // Clear the timer ID
// If a context menu (ours) is already visible, do nothing.
// This can happen if a 'contextmenu' event fired very quickly after pointerdown.
if (DesktopContextMenu.isVisible()) return;
// e.preventDefault(); // Already called in showContextMenu.
// Calling it here too early might interfere with other pointerdown logic if not careful.
// showContextMenu will call it.
showContextMenu(e); // Pass the original pointerdown event.
// targetIcon will be null, which is correct for desktop background.
}, LONG_PRESS_DURATION);
}
function clearLongPressTimer() {
if (longPressTimer) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
}
function handleDesktopPointerMoveForLongPress(e) {
if (longPressTimer) { // Only if a long press is pending
const deltaX = Math.abs(e.clientX - pointerDownClientX);
const deltaY = Math.abs(e.clientY - pointerDownClientY);
if (deltaX > MAX_MOVE_THRESHOLD || deltaY > MAX_MOVE_THRESHOLD) {
clearLongPressTimer(); // Moved too much, cancel long press
}
}
}
// --- End Long-press Helper Functions ---
function initDesktopContextMenu() {
desktopElement = document.getElementById('desktop');
if (!desktopElement) { console.error('ContextMenu: Desktop element not found.'); return; }
loadArrangePreferences();
loadDesktopPreferences();
createContextMenu(); // Create the menu structure once, keep it hidden
window.addEventListener('win9x:desktop-items-changed', () => {
if (!autoArrangeEnabled) return;
requestAnimationFrame(() => {
arrangeDesktopIcons(currentArrangeMode);
});
});
// For desktop browsers (right-click)
desktopElement.addEventListener('contextmenu', (e) => {
// Let native behavior through for text-editable elements (enables mobile text selection)
if (e.target.closest('textarea, input[type="text"], input[type="url"], input[type="search"], [contenteditable]')) {
return;
}
// If a long-press timer is active (meaning pointerdown happened but timer hasn't fired),
// and a contextmenu event fires (e.g. quick right-click), cancel the long-press.
if (longPressTimer) {
clearLongPressTimer();
}
// If the target of the right-click is an icon, do nothing here.
// The icon itself should have a contextmenu listener that calls
// window.DesktopContextMenu.show(e, iconElement).
if (e.target.closest('.desktop-icon')) {
// e.preventDefault(); // Optional: if icon handler doesn't, this would stop native menu on icon.
// But ideally, icon handler manages its own event.
return;
}
// If our custom menu is already visible (e.g., from a long press that also triggered contextmenu)
// or if clicking on elements that shouldn't get a desktop background menu.
if (DesktopContextMenu.isVisible() ||
e.target.closest('.window:not(.desktop-icon .window)') ||
e.target.closest('.display-properties-dialog') ||
e.target.closest('.desktop-context-menu')) {
e.preventDefault(); // Prevent native menu if ours is up or on disallowed element
return;
}
showContextMenu(e); // targetIcon will be null.
});
// For mobile long-press (and potentially mouse long-press if desired) on the desktop background
desktopElement.addEventListener('pointerdown', handleDesktopPointerDownForLongPress);
desktopElement.addEventListener('pointermove', handleDesktopPointerMoveForLongPress);
// Use document for pointerup/leave to catch cases where pointer is released outside desktopElement
// or finger leaves the screen.
document.addEventListener('pointerup', clearLongPressTimer);
document.addEventListener('pointerleave', clearLongPressTimer); // Catches mouse leaving window
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
if (contextMenuElement && contextMenuElement.style.display === 'block') {
hideContextMenu();
} else if (displayPropertiesDialog && desktopElement.contains(displayPropertiesDialog)) {
const closeBtn = displayPropertiesDialog.querySelector('.dialog-close-btn');
if (closeBtn) closeBtn.click();
else { displayPropertiesDialog.remove(); displayPropertiesDialog = null; }
}
}
});
if (autoArrangeEnabled) {
requestAnimationFrame(() => {
arrangeDesktopIcons(currentArrangeMode);
});
}
}
// Expose functions for long-press on icons (from other modules) and other interactions
if (!window.DesktopContextMenu) window.DesktopContextMenu = {};
window.DesktopContextMenu.show = showContextMenu;
window.DesktopContextMenu.showCustom = showCustomContextMenu;
window.DesktopContextMenu.hide = hideContextMenu;
window.DesktopContextMenu.isVisible = () => contextMenuElement && contextMenuElement.style.display === 'block';
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initDesktopContextMenu);
} else {
initDesktopContextMenu();
}
// General listener to hide menu on any pointerdown outside the menu.
// This needs to be distinct from handleClickOutsideContextMenu which is for 'click' events.
document.addEventListener('pointerdown', (e) => {
// Check if menu exists, is visible, and the click is NOT on the menu itself
if (contextMenuElement &&
contextMenuElement.style.display === 'block' &&
!e.target.closest('.desktop-context-menu')) {
// Use a small timeout to allow any click action on a menu item to process first
// before hideContextMenu potentially removes listeners or the item itself.
setTimeout(hideContextMenu, 50);
}
}, { capture: true }); // Use capture to catch the event early
})(window);