-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
7221 lines (6520 loc) · 296 KB
/
script.js
File metadata and controls
7221 lines (6520 loc) · 296 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
const APPS = {
notepad: { name:'Notepad', icon:'file-text', w:720, h:520, pinned:false },
explorer: { name:'File Explorer', icon:'folder-open', w:920, h:600, pinned:true },
settings: { name:'Settings', icon:'settings', w:820, h:600, pinned:true },
terminal: { name:'Terminal', icon:'terminal', w:740, h:500, pinned:false },
calculator: { name:'Calculator', icon:'calculator', w:320, h:510, pinned:false },
browser: { name:'Edge', icon:'globe', w:1000, h:680, pinned:false },
paint: { name:'Paint', icon:'palette', w:860, h:600, pinned:false },
music: { name:'Music', icon:'music', w:480, h:560, pinned:true },
recycle: { name:'Recycle Bin', icon:'trash-2', w:440, h:460, pinned:false },
developer: { name:'Developer', icon:'user-round-cog', w:1000, h:570, pinned:false},
taskmgr: { name:'Task Manager', icon:'activity', w:520, h:480, pinned:false },
calendar: { name:'Calendar', icon:'calendar-days', w:420, h:580, pinned:false },
weather: { name:'Weather', icon:'cloud-sun', w:380, h:500, pinned:false },
clock: { name:'Clock', icon:'clock', w:500, h:500, pinned:false },
gallery: { name:'Gallery', icon:'images', w:720, h:520, pinned:false },
'gallery-viewer': { name:'Image Viewer', icon:'image', w:900, h:700, pinned:false },
'video-player': { name:'Video Player', icon:'play-circle', w:1000, h:700, pinned:false },
video: { name:'Videos', icon:'video', w:800, h:560, pinned:false },
mail: { name:'Mail', icon:'mail', w:820, h:580, pinned:false },
chat: { name:'Chat', icon:'message-circle', w:680, h:560, pinned:false },
};
function lucideIconHtml(name, size = 18) {
const s = typeof size === 'number' ? size + 'px' : size;
return `<i data-lucide="${name}" class="lucide-inline" style="width:${s};height:${s}"></i>`;
}
function refreshLucideIcons(root) {
if (typeof lucide === 'undefined' || !lucide.createIcons) return;
const opts = { attrs: { 'stroke-width': 1.75 } };
if (root && root.nodeType === 1) opts.root = root;
try {
lucide.createIcons(opts);
} catch (e) {
try { lucide.createIcons(); } catch (e2) {}
}
}
const WALLPAPERS = [
{ name:'Horizon', bg:'linear-gradient(125deg,#0c1929 0%,#1a3a52 38%,#0d2137 100%)' },
{ name:'Aurora', bg:'linear-gradient(135deg,#0a1628 0%,#1e3a5f 45%,#0f2840 100%)' },
{ name:'Nebula', bg:'radial-gradient(ellipse 100% 80% at 20% 20%,#4c1d95 0%,transparent 50%),radial-gradient(ellipse 80% 60% at 80% 70%,#0e7490 0%,transparent 45%),linear-gradient(160deg,#0f172a 0%,#1e1b4b 100%)' },
{ name:'Sunset', bg:'linear-gradient(160deg,#ff6b6b 0%,#ff8e53 40%,#ffd93d 100%)' },
{ name:'Forest', bg:'linear-gradient(135deg,#134e5e 0%,#71b280 100%)' },
{ name:'Purple', bg:'linear-gradient(135deg,#2d1b69 0%,#8b2fc9 100%)' },
{ name:'Ocean', bg:'linear-gradient(135deg,#005c97 0%,#363795 100%)' },
{ name:'Rose', bg:'linear-gradient(135deg,#f953c6 0%,#b91d73 100%)' },
{ name:'Carbon', bg:'linear-gradient(180deg,#18181b 0%,#0a0a0b 100%)' },
{ name:'Volcano', bg:'linear-gradient(160deg,#8b0000 0%,#ff4500 50%,#2f1f0f 100%)' },
{ name:'Arctic', bg:'linear-gradient(160deg,#e8f4f8 0%,#a8d8ea 50%,#d0e8f0 100%)' },
{ name:'Midnight', bg:'linear-gradient(135deg,#0f0c29 0%,#302b63 50%,#24243e 100%)' },
{ name:'Mint', bg:'linear-gradient(135deg,#134e4a 0%,#44bfaa 100%)' },
{ name:'Peach', bg:'linear-gradient(135deg,#ffecd2 0%,#fcb69f 100%)' },
{ name:'Lavender', bg:'linear-gradient(135deg,#e6e9f0 0%,#c9d6ff 100%)' },
{ name:'Ember', bg:'linear-gradient(160deg,#232526 0%,#414345 50%,#181a1b 100%)' },
{ name:'Candy', bg:'linear-gradient(160deg,#ff9a9e 0%,#fecfef 50%,#fad0c4 100%)' },
{ name:'Matrix', bg:'linear-gradient(180deg,#0d1f0d 0%,#0a330a 50%,#051505 100%)' },
];
const ACCENT_COLORS = [
'#0078d4','#8764b8','#567c34','#ca5010','#008b8b','#c43e1c','#69797e','#038387',
'#e74856','#ff8c00','#00b294','#6b69de','#a426a4','#d1342a','#e3008c','#567c34'
];
/*
CUSTOM MODAL DIALOG
*/
function showModal(options) {
return new Promise(function(resolve) {
var modal = document.getElementById('wos-modal');
var title = document.getElementById('wos-modal-title');
var message = document.getElementById('wos-modal-message');
var inputContainer = document.getElementById('wos-modal-input-container');
var input = document.getElementById('wos-modal-input');
var btnCancel = document.getElementById('wos-modal-btn-cancel');
var btnConfirm = document.getElementById('wos-modal-btn-confirm');
title.textContent = options.title || '';
message.textContent = options.message || '';
if (options.input) {
inputContainer.style.display = 'block';
input.value = options.defaultValue || '';
input.placeholder = options.placeholder || '';
} else {
inputContainer.style.display = 'none';
}
if (options.cancelText) btnCancel.textContent = options.cancelText;
if (options.confirmText) btnConfirm.textContent = options.confirmText;
if (options.danger) {
btnConfirm.style.background = '#c42b1c';
} else {
btnConfirm.style.background = '';
}
modal.style.display = 'flex';
if (options.input) {
setTimeout(function() { input.focus(); input.select(); }, 50);
}
function cleanup() {
modal.style.display = 'none';
btnCancel.onclick = null;
btnConfirm.onclick = null;
input.onkeydown = null;
}
btnCancel.onclick = function() {
cleanup();
resolve(null);
};
btnConfirm.onclick = function() {
cleanup();
resolve(options.input ? input.value : true);
};
input.onkeydown = function(e) {
if (e.key === 'Enter') {
cleanup();
resolve(input.value);
} else if (e.key === 'Escape') {
cleanup();
resolve(null);
}
};
});
}
/*
VIRTUAL FILE SYSTEM
*/
let FS = JSON.parse(localStorage.getItem('wos_fs') || 'null') || {
'/': { type:'dir' },
'/Desktop': { type:'dir' },
'/Documents':{ type:'dir' },
'/Pictures': { type:'dir' },
'/Downloads':{ type:'dir' },
'/Music': { type:'dir' },
'/Documents/Welcome.txt': {
type:'file', ext:'txt',
content:'Welcome to WebOS 12!\n\nThis is your virtual file system.\nYou can create, edit, and delete files.\n\nEnjoy the experience!',
modified: Date.now()
},
'/Documents/Notes.txt': {
type:'file', ext:'txt',
content:'My Notes\n========\n\n- Learn WebOS\n- Try all the apps\n- Customize the wallpaper',
modified: Date.now()
},
'/Desktop/Readme.txt': {
type:'file', ext:'txt',
content: 'Welcome to WebOS 12\n\nSYSTEM CONTROLS:\n- Double-click desktop icons to launch applications.\n- Use the Taskbar at the bottom to switch between open windows.\n- Click the Clock area to view the Notification Center.\n\nDEVELOPER TOOLS:\n- Open the "Developer" app to view system architecture and kernel stats.\n- Use the Terminal for low-level system commands.\n\nPRO TIPS:\n- You can install this OS as a PWA via your browser address bar.\n- Right-click (or long-press) may reveal additional context menus.\n\nEnjoy your refined web experience!',
modified: Date.now()
},
};
function saveFS() {
try { localStorage.setItem('wos_fs', JSON.stringify(FS)); } catch(e){}
// Sync to server
try {
const localStorageData = {};
localStorageData['wos_fs'] = FS;
fetch('/api/localstorage/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(localStorageData)
}).catch(() => {});
} catch(e) {}
queueMicrotask(() => notifyFsChanged());
}
const explorerRefreshers = {};
function notifyFsChanged() {
try {
buildDesktopIcons();
Object.keys(explorerRefreshers).forEach(id => {
const fn = explorerRefreshers[id];
if (typeof fn === 'function') { try { fn(); } catch (e) {} }
});
} catch (e) {}
}
function fsMovePath(srcPath, destDirPath) {
srcPath = normPath(srcPath);
destDirPath = normPath(destDirPath);
const name = srcPath.split('/').filter(Boolean).pop();
if (!name || !FS[srcPath]) return false;
const newPath = destDirPath === '/' ? '/' + name : destDirPath + '/' + name;
if (FS[newPath]) {
showNotification('File Explorer', 'A file or folder with that name already exists here.', 'folder');
return false;
}
const normSrc = normPath(srcPath);
if (newPath === normSrc) return true;
if (normSrc !== '/' && (newPath === normSrc || newPath.startsWith(normSrc + '/'))) {
showNotification('File Explorer', 'Cannot move a folder into itself.', 'alert-triangle');
return false;
}
FS[newPath] = FS[srcPath];
delete FS[srcPath];
const pn = normSrc + '/';
for (const [k, v] of Object.entries(FS)) {
if (k.startsWith(pn)) {
const np = normPath(newPath) + '/' + k.slice(pn.length);
FS[np] = v;
delete FS[k];
}
}
// Sync move to server
try {
fetch('/api/file/move', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ srcPath, destPath: newPath })
}).catch(() => {});
} catch(e) {}
saveFS();
return true;
}
function fsListDir(path) {
path = normPath(path);
const prefix = path === '/' ? '/' : path + '/';
const items = [];
for (const [k, v] of Object.entries(FS)) {
if (k === path) continue;
if (!k.startsWith(prefix)) continue;
const rest = k.slice(prefix.length);
if (!rest.includes('/')) items.push({ path:k, name:rest, ...v });
}
return items;
}
function normPath(p) {
if (!p || p === '/') return '/';
return p.replace(/\/+$/, '');
}
function fsParent(p) {
p = normPath(p);
if (p === '/') return '/';
const parts = p.split('/');
parts.pop();
return parts.join('/') || '/';
}
function fsCreate(dirPath, name, type, content='') {
const p = normPath(dirPath) + '/' + name;
if (FS[p]) return false;
FS[p] = type === 'dir'
? { type:'dir' }
: { type:'file', ext: name.split('.').pop() || 'txt', content, modified: Date.now() };
saveFS();
return p;
}
function fsDelete(p) {
const pn = normPath(p) + '/';
for (const k of Object.keys(FS)) {
if (k === p || k.startsWith(pn)) delete FS[k];
}
saveFS();
}
let RECYCLE_BIN = JSON.parse(localStorage.getItem('wos_recycle') || '[]');
function saveRecycleBin() {
try { localStorage.setItem('wos_recycle', JSON.stringify(RECYCLE_BIN)); } catch (e) {}
}
function recyclePath(path) {
const norm = normPath(path);
if (!FS[norm]) return false;
const keys = [norm];
const pn = norm + '/';
for (const k of Object.keys(FS)) {
if (k.startsWith(pn)) keys.push(k);
}
const snapshot = {};
keys.forEach(k => { snapshot[k] = JSON.parse(JSON.stringify(FS[k])); });
const id = 'rb_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9);
RECYCLE_BIN.push({
id,
root: norm,
name: norm.split('/').filter(Boolean).pop() || norm,
deleted: Date.now(),
snapshot
});
fsDelete(norm);
saveRecycleBin();
return true;
}
function restoreRecycleEntry(entry) {
const paths = Object.keys(entry.snapshot).sort((a, b) => a.split('/').length - b.split('/').length);
for (const p of paths) {
if (FS[p]) {
showNotification('Recycle Bin', 'Cannot restore: ' + p.split('/').pop() + ' already exists.', 'alert-circle');
return false;
}
}
paths.forEach(p => { FS[p] = JSON.parse(JSON.stringify(entry.snapshot[p])); });
RECYCLE_BIN = RECYCLE_BIN.filter(x => x.id !== entry.id);
saveRecycleBin();
saveFS();
return true;
}
function purgeRecycleEntry(id) {
RECYCLE_BIN = RECYCLE_BIN.filter(x => x.id !== id);
saveRecycleBin();
}
function emptyRecycleBinPermanently() {
RECYCLE_BIN = [];
saveRecycleBin();
}
function fsRename(p, newName) {
const parent = fsParent(p);
const newPath = normPath(parent) + '/' + newName;
const old = FS[p];
if (!old) return;
FS[newPath] = old;
delete FS[p];
// rename children
const pn = normPath(p) + '/';
for (const [k, v] of Object.entries(FS)) {
if (k.startsWith(pn)) {
const np = normPath(newPath) + '/' + k.slice(pn.length);
FS[np] = v;
delete FS[k];
}
}
saveFS();
}
function fsWrite(p, content) {
if (FS[p]) { FS[p].content = content; FS[p].modified = Date.now(); saveFS(); }
}
function fileTypeLucide(name, type) {
if (type === 'dir') return 'folder';
const ext = (name.split('.').pop() || '').toLowerCase();
const map = {
txt: 'file-text', md: 'file-text', js: 'file-code', html: 'file-code', css: 'palette',
json: 'braces', png: 'image', jpg: 'image', gif: 'image', mp3: 'music', mp4: 'video',
zip: 'archive', pdf: 'file-text', exe: 'cpu'
};
return map[ext] || 'file';
}
/*
SETTINGS STATE
*/
let state = JSON.parse(localStorage.getItem('wos_state') || '{}');
const isNewInstall = !state.installed;
if (isNewInstall) {
state = {
sessionId: Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
installed: false,
theme: 'dark',
wallpaper: 0,
accent: '#0078d4',
iconLayout: {},
brightness: 100,
notificationsEnabled: true,
transparencyEnabled: true,
username: '',
pinnedApps: [],
password: ''
};
}
if (!state.sessionId) { state.sessionId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); saveState(); }
state.theme = state.theme || 'dark';
state.wallpaper = state.wallpaper ?? 0;
state.accent = state.accent || '#0078d4';
if (!state.iconLayout || typeof state.iconLayout !== 'object') state.iconLayout = {};
state.brightness = Math.round(Math.max(10, Math.min(100, Number(state.brightness) || 100)));
state.notificationsEnabled = state.notificationsEnabled !== false;
state.transparencyEnabled = state.transparencyEnabled !== false;
/* €€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€
FIREBASE CONFIG
€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€ */
const firebaseConfig = {
apiKey: "AIzaSyBfOtVWIMaZjyKGT3BTtljiADXEkrPE2qA",
authDomain: "webos-a4010.firebaseapp.com",
projectId: "webos-a4010",
storageBucket: "webos-a4010.firebasestorage.app",
messagingSenderId: "338821714456",
appId: "1:338821714456:web:e6bf9edcd6a901b875e96d"
};
let db = null;
let currentUserEmail = null;
let currentUserId = null;
function initFirebase() {
console.log('Firebase loaded:', typeof firebase !== 'undefined');
if (typeof firebase === 'undefined') return;
try {
firebase.initializeApp(firebaseConfig);
db = firebase.firestore();
console.log('Firestore initialized:', !!db);
} catch (e) {
console.log('Firebase init error:', e);
}
let storedId = localStorage.getItem('wos_user_id');
if (!storedId || !/^\d{3}$/.test(storedId)) {
storedId = String(Math.floor(Math.random() * 900) + 100);
localStorage.setItem('wos_user_id', storedId);
}
currentUserId = storedId;
console.log('User ID:', currentUserId);
window.addEventListener('beforeunload', () => {
if (db && currentUserId) {
firebase.firestore().collection('chat_users').doc(currentUserId).delete();
}
});
setupBackgroundListeners();
}
let bgListenersReady = false;
function setupBackgroundListeners() {
if (!db || !currentUserId || bgListenersReady) return;
bgListenersReady = true;
const bgUsername = (state && state.username) ? state.username.toLowerCase().replace(/\s/g, '') : 'user';
const bgEmail = bgUsername + '.' + currentUserId + '@webos';
const lastNotifiedMailId = localStorage.getItem('last_notified_mail') || '';
const lastNotifiedChatId = localStorage.getItem('last_notified_chat') || '';
let initialMailLoaded = false;
let initialChatLoaded = false;
const q = firebase.firestore().collection('mail').where('to', '==', bgEmail).where('unread', '==', true);
q.onSnapshot((snapshot) => {
if (!initialMailLoaded) {
initialMailLoaded = true;
return;
}
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
const email = change.doc.data();
if (email.id !== lastNotifiedMailId) {
showNotification('Mail', `${email.from}: ${email.subject}`, 'mail');
localStorage.setItem('last_notified_mail', email.id);
}
}
});
});
firebase.firestore().collection('chat_messages').orderBy('timestamp', 'desc').limit(1).onSnapshot((snapshot) => {
if (!initialChatLoaded) {
initialChatLoaded = true;
return;
}
if (!snapshot.empty) {
const lastMsg = snapshot.docs[0].data();
if (lastMsg.userId !== currentUserId && lastMsg.id !== lastNotifiedChatId) {
showNotification('Chat', `${lastMsg.user}: ${lastMsg.text}`, 'message-circle');
localStorage.setItem('last_notified_chat', lastMsg.id);
}
}
});
}
if (!isNewInstall) {
state.username = (state.username && String(state.username).trim()) || 'User';
}
state.timezone = state.timezone || 'Africa/Nairobi';
state.region = state.region || 'east-africa';
if (!Array.isArray(state.pinnedApps)) {
state.pinnedApps = Object.keys(APPS).filter(id => APPS[id].pinned);
}
state.password = state.password || '';
state.locked = state.locked === true;
state.profilePicture = state.profilePicture || 'default';
const TIMEZONE_DATA = {
'Africa/Nairobi': { offset: 3, name: 'EAT' },
'Africa/Lagos': { offset: 1, name: 'WAT' },
'Africa/Johannesburg': { offset: 2, name: 'SAST' },
'Africa/Cairo': { offset: 2, name: 'EET' },
'Europe/London': { offset: 0, name: 'GMT' },
'Europe/Paris': { offset: 1, name: 'CET' },
'Europe/Moscow': { offset: 3, name: 'MSK' },
'Europe/Berlin': { offset: 1, name: 'CET' },
'Europe/Madrid': { offset: 1, name: 'CET' },
'Asia/Riyadh': { offset: 3, name: 'AST' },
'Asia/Kolkata': { offset: 5.5, name: 'IST' },
'Asia/Bangkok': { offset: 7, name: 'ICT' },
'Asia/Tokyo': { offset: 9, name: 'JST' },
'Asia/Shanghai': { offset: 8, name: 'CST' },
'Asia/Dubai': { offset: 4, name: 'GST' },
'America/New_York': { offset: -5, name: 'EST' },
'America/Los_Angeles': { offset: -8, name: 'PST' },
'America/Sao_Paulo': { offset: -3, name: 'BRT' },
'America/Mexico_City': { offset: -6, name: 'CST' },
'America/Toronto': { offset: -5, name: 'EST' },
'America/Jamaica': { offset: -5, name: 'EST' },
'Australia/Sydney': { offset: 10, name: 'AEST' },
'Pacific/Auckland': { offset: 12, name: 'NZST' }
};
function saveState() { localStorage.setItem('wos_state', JSON.stringify(state)); }
function escapeHtml(s) {
return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
function applyBrightness(pct) {
const v = Math.round(Math.max(10, Math.min(100, Number(pct) || 100)));
state.brightness = v;
document.body.style.filter = `brightness(${v}%)`;
saveState();
document.querySelectorAll('input[data-brightness-slider]').forEach(el => { el.value = String(v); });
}
function applyTransparency() {
document.documentElement.classList.toggle('reduce-transparency', state.transparencyEnabled === false);
}
function updateUsernameUI() {
const el = document.getElementById('start-username');
if (el) el.textContent = state.username;
const avatarEl = document.querySelector('.user-avatar');
if (avatarEl && state.username) {
avatarEl.textContent = state.username.charAt(0).toUpperCase();
}
}
function launchOrFocusApp(appId) {
const wins = [...windowsMap.entries()].filter(([, w]) => w.appId === appId);
const openNorm = wins.find(([, w]) => w.state !== 'minimized');
if (openNorm) { focusWin(openNorm[0]); return; }
const min = wins.find(([, w]) => w.state === 'minimized');
if (min) { restoreWin(min[0]); return; }
launchApp(appId);
}
function togglePinToTaskbar(appId) {
const p = [...(state.pinnedApps || [])];
const i = p.indexOf(appId);
if (i >= 0) p.splice(i, 1);
else if (p.length < 16) p.push(appId);
state.pinnedApps = p;
saveState();
updateTaskbar();
}
function youtubeIdFromUrl(raw) {
let u = String(raw || '').trim();
if (!u) return null;
if (!/^https?:\/\//i.test(u)) u = 'https://' + u;
try {
const url = new URL(u);
const h = url.hostname.replace(/^www\./, '');
if (h === 'youtu.be') {
const id = url.pathname.replace(/^\//, '').split('/')[0];
return id && id.length >= 6 ? id : null;
}
if (h === 'youtube.com' || h === 'm.youtube.com' || h === 'www.youtube.com' || h.endsWith('.youtube.com')) {
if (url.pathname.startsWith('/watch')) return url.searchParams.get('v');
if (url.pathname.startsWith('/embed/')) return url.pathname.split('/')[2];
if (url.pathname.startsWith('/shorts/')) return url.pathname.split('/')[2];
if (url.pathname.startsWith('/live/')) return url.pathname.split('/')[2];
}
} catch (e) {}
return null;
}
function applyTheme(t) {
state.theme = t;
document.documentElement.setAttribute('data-theme', t);
saveState();
}
function applyWallpaper(idx) {
const i = Math.max(0, Math.min(Number(idx) || 0, WALLPAPERS.length - 1));
state.wallpaper = i;
document.getElementById('desktop').style.backgroundImage = '';
document.getElementById('desktop').style.background = WALLPAPERS[i].bg;
saveState();
}
function applyAccent(color) {
state.accent = color;
document.documentElement.style.setProperty('--accent', color);
document.documentElement.style.setProperty('--accent-hover', color);
// Create lighter accent for gradients
var r = parseInt(color.slice(1,3), 16);
var g = parseInt(color.slice(3,5), 16);
var b = parseInt(color.slice(5,7), 16);
var lighter = 'rgba(' + Math.min(255, r + 60) + ',' + Math.min(255, g + 60) + ',' + Math.min(255, b + 60) + ',0.8)';
document.documentElement.style.setProperty('--accent-light', lighter);
saveState();
}
/*
WINDOW MANAGER
*/
const winsLayer = document.getElementById('windows-layer');
let windowsMap = new Map(); // id ’ { el, appId, state:'normal'|'minimized'|'maximized', prevBounds }
let focusedWin = null;
let zTop = 100;
let winCount = 0;
function createWindow(appId, extra = {}) {
const app = APPS[appId];
if (!app) return;
const id = `win_${++winCount}`;
const vw = winsLayer.offsetWidth || window.innerWidth;
const vh = winsLayer.offsetHeight || (window.innerHeight - 48);
const w = Math.min(app.w, vw - 40);
const h = Math.min(app.h, vh - 40);
const x = Math.round((vw - w) / 2) + (winCount % 5) * 24;
const y = Math.round((vh - h) / 2) + (winCount % 5) * 20;
const el = document.createElement('div');
el.className = 'window';
el.id = id;
el.style.cssText = `width:${w}px;height:${h}px;left:${x}px;top:${y}px;z-index:${++zTop}`;
// Motion One animation for opening
if (typeof motion !== 'undefined') {
if (launchOrigin) {
const originX = launchOrigin.x - x;
const originY = launchOrigin.y - y;
motion(el, {
from: { transform: `translate(${originX}px, ${originY}px) scale(0.1)`, opacity: 0 },
to: { transform: 'translate(0, 0) scale(1)', opacity: 1 },
duration: 400,
easing: 'ease-out',
});
launchOrigin = null;
} else {
motion(el, {
from: { transform: 'scale(0.9)', opacity: 0 },
to: { transform: 'scale(1)', opacity: 1 },
duration: 250,
easing: 'ease-out',
});
}
}
// Build title bar
el.innerHTML = `
<div class="win-titlebar" id="${id}_tb">
<span class="win-icon">${lucideIconHtml(app.icon, 15)}</span>
<span class="win-title">${extra.title || app.name}</span>
<div class="win-ctrls">
<div class="wc-btn wc-min" title="Minimize" data-id="${id}">
<svg viewBox="0 0 10 1"><rect width="10" height="1"/></svg>
</div>
<div class="wc-btn wc-max" title="Maximize" data-id="${id}">
<svg viewBox="0 0 10 10"><rect width="10" height="10" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>
</div>
<div class="wc-btn wc-close" title="Close" data-id="${id}">
<svg viewBox="0 0 10 10"><line x1="0" y1="0" x2="10" y2="10" stroke="currentColor" stroke-width="1.4"/>
<line x1="10" y1="0" x2="0" y2="10" stroke="currentColor" stroke-width="1.4"/></svg>
</div>
</div>
</div>
<div class="win-content" id="${id}_content"></div>
<!-- Resize handles -->
<div class="rh rh-n" data-id="${id}" data-dir="n"></div>
<div class="rh rh-s" data-id="${id}" data-dir="s"></div>
<div class="rh rh-e" data-id="${id}" data-dir="e"></div>
<div class="rh rh-w" data-id="${id}" data-dir="w"></div>
<div class="rh rh-ne" data-id="${id}" data-dir="ne"></div>
<div class="rh rh-nw" data-id="${id}" data-dir="nw"></div>
<div class="rh rh-se" data-id="${id}" data-dir="se"></div>
<div class="rh rh-sw" data-id="${id}" data-dir="sw"></div>
`;
winsLayer.appendChild(el);
refreshLucideIcons(el);
const winData = { el, appId, title: extra.title || app.name, state:'normal', prevBounds:null };
windowsMap.set(id, winData);
// Render app content
const content = document.getElementById(`${id}_content`);
renderApp(appId, content, id, extra);
// Wire controls
el.querySelector('.wc-min').addEventListener('click', () => minimizeWin(id));
el.querySelector('.wc-max').addEventListener('click', () => toggleMaximize(id));
el.querySelector('.wc-close').addEventListener('click',() => closeWin(id));
// Focus on click
el.addEventListener('mousedown', () => focusWin(id), true);
// Drag
initDrag(el.querySelector('.win-titlebar'), el, id);
// Resize
el.querySelectorAll('.rh').forEach(h => initResize(h, el, id));
focusWin(id);
updateTaskbar();
return id;
}
function focusWin(id) {
if (focusedWin === id) return;
if (focusedWin) {
const prev = windowsMap.get(focusedWin);
if (prev) prev.el.classList.remove('focused');
}
focusedWin = id;
const win = windowsMap.get(id);
if (!win) return;
win.el.classList.add('focused');
win.el.style.zIndex = ++zTop;
updateTaskbar();
}
function minimizeWin(id) {
const win = windowsMap.get(id);
if (!win) return;
// Find target position (taskbar button)
const app = APPS[win.appId];
let targetX, targetY;
const taskbarBtns = document.querySelectorAll('#taskbar-windows .tb-btn');
for (let btn of taskbarBtns) {
if (btn.title === (win.title || app.name)) {
const rect = btn.getBoundingClientRect();
targetX = rect.left + rect.width / 2;
targetY = rect.top;
break;
}
}
if (!targetX) {
targetX = window.innerWidth / 2;
targetY = window.innerHeight - 60;
}
const winRect = win.el.getBoundingClientRect();
const startX = winRect.left + winRect.width / 2;
const startY = winRect.top + winRect.height / 2;
const translateX = targetX - startX;
const translateY = targetY - startY;
if (typeof motion !== 'undefined') {
motion(win.el, {
from: { transform: 'translate(0, 0) scale(1)', opacity: 1 },
to: { transform: `translate(${translateX}px, ${translateY}px) scale(0.2)`, opacity: 0 },
duration: 300,
easing: 'ease-in',
}).finished.then(() => {
win.state = 'minimized';
win.el.classList.add('minimized');
win.el.style.transform = '';
if (focusedWin === id) { focusedWin = null; }
updateTaskbar();
});
} else {
win.el.classList.add('minimizing');
setTimeout(() => {
win.state = 'minimized';
win.el.classList.remove('minimizing');
win.el.classList.add('minimized');
if (focusedWin === id) { focusedWin = null; }
updateTaskbar();
}, 300);
}
}
function restoreWin(id) {
const win = windowsMap.get(id);
if (!win) return;
win.state = 'normal';
win.el.classList.remove('minimized','maximized','snapped-left','snapped-right');
// Calculate target position for restore animation
let targetX, targetY;
if (win.prevBounds) {
targetX = win.prevBounds.x + win.prevBounds.w / 2;
targetY = win.prevBounds.y + win.prevBounds.h / 2;
} else {
const vw = winsLayer.offsetWidth || window.innerWidth;
const vh = winsLayer.offsetHeight || (window.innerHeight - 48);
targetX = vw / 2;
targetY = vh / 2;
}
// Find taskbar button as origin
const app = APPS[win.appId];
let startX = window.innerWidth / 2, startY = window.innerHeight - 60;
const taskbarBtns = document.querySelectorAll('#taskbar-windows .tb-btn');
for (let btn of taskbarBtns) {
if (btn.title === (win.title || app.name)) {
const rect = btn.getBoundingClientRect();
startX = rect.left + rect.width / 2;
startY = rect.top;
break;
}
}
const translateX = targetX - startX;
const translateY = targetY - startY;
if (win.prevBounds) {
const b = win.prevBounds;
win.el.style.cssText = `width:${b.w}px;height:${b.h}px;left:${b.x}px;top:${b.y}px;z-index:${win.el.style.zIndex}`;
win.prevBounds = null;
}
if (typeof motion !== 'undefined') {
motion(win.el, {
from: { transform: `translate(${translateX}px, ${translateY}px) scale(0.2)`, opacity: 0 },
to: { transform: 'translate(0, 0) scale(1)', opacity: 1 },
duration: 400,
easing: 'ease-out',
});
}
focusWin(id);
updateTaskbar();
}
function toggleMaximize(id) {
const win = windowsMap.get(id);
if (!win) return;
if (win.state === 'maximized') {
restoreWin(id);
} else {
const el = win.el;
win.prevBounds = { x:el.offsetLeft, y:el.offsetTop, w:el.offsetWidth, h:el.offsetHeight };
win.state = 'maximized';
el.classList.remove('minimized','snapped-left','snapped-right');
if (typeof motion !== 'undefined') {
motion(el, {
from: { transform: 'scale(1)' },
to: { transform: 'scale(1.08)' },
duration: 150,
easing: 'ease-out',
}).finished.then(() => {
el.classList.add('maximized');
motion(el, {
from: { transform: 'scale(1.08)' },
to: { transform: 'scale(1)' },
duration: 150,
easing: 'ease-in',
});
focusWin(id);
updateTaskbar();
});
} else {
el.classList.add('maximizing');
setTimeout(() => {
el.classList.add('maximized');
el.classList.remove('maximizing');
focusWin(id);
updateTaskbar();
}, 120);
}
}
}
function closeWin(id) {
const win = windowsMap.get(id);
if (!win) return;
delete explorerRefreshers[id];
// Call cleanup if app has one
if (win.container && win.container._taskmgrCleanup) {
win.container._taskmgrCleanup();
}
// Cleanup chat user when closing chat window
if (win.app === 'chat' && db && currentUserId) {
firebase.firestore().collection('chat_users').doc(currentUserId).delete().catch(() => {});
}
if (typeof motion !== 'undefined') {
motion(win.el, {
from: { transform: 'scale(1)', opacity: 1 },
to: { transform: 'scale(0.9)', opacity: 0 },
duration: 150,
easing: 'ease-in',
}).finished.then(() => {
win.el.remove();
windowsMap.delete(id);
if (focusedWin === id) focusedWin = null;
updateTaskbar();
});
} else {
win.el.style.animation = 'fadeOut .12s ease forwards';
setTimeout(() => {
win.el.remove();
windowsMap.delete(id);
if (focusedWin === id) focusedWin = null;
updateTaskbar();
}, 120);
}
}
function taskbarClickWin(id) {
const win = windowsMap.get(id);
if (!win) return;
if (win.state === 'minimized') {
restoreWin(id);
} else if (focusedWin === id) {
minimizeWin(id);
} else {
focusWin(id);
}
}
/* €€ Drag €€ */
function initDrag(handle, winEl, id) {
let startX, startY, startL, startT, dragging = false;
const snap = document.getElementById('snap-overlay');
handle.addEventListener('mousedown', e => {
if (e.target.closest('.wc-btn')) return;
const win = windowsMap.get(id);
if (!win || win.state === 'maximized') {
// Un-maximize on drag from max
if (win && win.state === 'maximized') {
const rect = winEl.getBoundingClientRect();
const newW = win.prevBounds?.w || winEl.offsetWidth;
const newH = win.prevBounds?.h || winEl.offsetHeight;
win.state = 'normal';
winEl.classList.remove('maximized');
winEl.style.width = newW + 'px';
winEl.style.height = newH + 'px';
winEl.style.left = (e.clientX - newW/2) + 'px';
winEl.style.top = '0px';
win.prevBounds = null;
} else return;
}
dragging = true;
startX = e.clientX; startY = e.clientY;
startL = winEl.offsetLeft; startT = winEl.offsetTop;
e.preventDefault();
});
document.addEventListener('mousemove', e => {
if (!dragging) return;
const win = windowsMap.get(id);
if (!win) return;
const dx = e.clientX - startX, dy = e.clientY - startY;
let nx = startL + dx, ny = startT + dy;
// Constrain to viewport
const vw = winsLayer.offsetWidth;
const vh = winsLayer.offsetHeight;
nx = Math.max(-winEl.offsetWidth + 40, Math.min(vw - 40, nx));
ny = Math.max(0, Math.min(vh - 36, ny));
winEl.style.left = nx + 'px';
winEl.style.top = ny + 'px';
// Snap zones
if (e.clientX < 4) {
snap.style.cssText = 'display:block;left:0;top:0;width:50%;height:100%;';
} else if (e.clientX > window.innerWidth - 4) {
snap.style.cssText = 'display:block;left:50%;top:0;width:50%;height:100%;';
} else if (e.clientY < 4) {
snap.style.cssText = 'display:block;left:0;top:0;width:100%;height:100%;';
} else {
snap.style.display = 'none';
}
});
document.addEventListener('mouseup', e => {
if (!dragging) return;
dragging = false;
snap.style.display = 'none';
const win = windowsMap.get(id);
if (!win) return;
// Apply snap
const vw = winsLayer.offsetWidth;
const vh = winsLayer.offsetHeight;
if (e.clientX < 4) {
win.prevBounds = { x:winEl.offsetLeft, y:winEl.offsetTop, w:winEl.offsetWidth, h:winEl.offsetHeight };
winEl.classList.add('snapped-left');
win.state = 'snapped';