-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchrome.js
More file actions
1975 lines (1926 loc) · 136 KB
/
Copy pathchrome.js
File metadata and controls
1975 lines (1926 loc) · 136 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
'use strict';
const THEMES = ['materia', 'crimson', 'cobalt', 'amethyst', 'obsidian'];
let currentTheme = localStorage.getItem('materia-theme') || 'materia';
let forceRightClick = localStorage.getItem('materia-rightclick') !== '0';
function newtabUrl() { const rel = 'newtab.html?t=' + currentTheme; try { return new URL(rel, location.href).href; } catch (_) { return rel; } }
const NT_PRELOAD = (function () { try { return new URL('mm-nt-preload.js', location.href).href; } catch (_) { return ''; } })();
const OMNI_ICONS = {
search: '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>',
lock: '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>',
warn: '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 2 20h20z"/><path d="M12 9v5M12 17.4v.1"/></svg>'
};
// Unblock copy/right-click/select WITHOUT breaking the page's own drag-and-drop. We deliberately do NOT
// stopImmediatePropagation on 'dragstart' — doing so fired before the page's dragstart handler and killed
// legit in-page DnD (dragging an image into a drop box never populated dataTransfer). Instead we defeat the
// common image-drag blocks passively: null document.ondragstart (property-handler blocks) + force img
// -webkit-user-drag:auto (CSS blocks). Listener-based dragstart blockers are left alone (rare, not worth
// breaking every web app's drag-and-drop for).
const UNBLOCK_JS = "(function(){if(window.__mmu)return;window.__mmu=1;function a(e){e.stopImmediatePropagation();}['contextmenu','selectstart','copy','cut'].forEach(function(t){window.addEventListener(t,a,true);document.addEventListener(t,a,true);});try{document.oncontextmenu=null;document.onselectstart=null;document.oncopy=null;document.ondragstart=null;}catch(_){}var s=document.createElement('style');s.textContent='*{-webkit-user-select:text!important;user-select:text!important;-webkit-touch-callout:default!important}img{-webkit-user-drag:auto!important}';(document.head||document.documentElement).appendChild(s);})();";
// Prefill an AI chat's input box with the start-page query, once the page renders.
function aiPrefillJS(query) {
return '(function(){var Q=' + JSON.stringify(query) + ';var n=0;var iv=setInterval(function(){n++;'
+ 'var el=document.querySelector(\'div.ProseMirror[contenteditable="true"], rich-textarea div[contenteditable="true"], textarea, div[contenteditable="true"], input[type="text"]\');'
+ 'if(el&&(el.offsetParent!==null||el.getClientRects().length)){clearInterval(iv);try{el.focus();'
+ 'if(el.isContentEditable){el.textContent=Q;el.dispatchEvent(new InputEvent("input",{bubbles:true,inputType:"insertText",data:Q}));}'
+ 'else{var pr=el.tagName==="TEXTAREA"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;var st=Object.getOwnPropertyDescriptor(pr,"value").set;st.call(el,Q);el.dispatchEvent(new Event("input",{bubbles:true}));}'
+ '}catch(e){}}if(n>40){clearInterval(iv);}},250);})();';
}
function injectAIPrefill(view, query) { try { view.executeJavaScript(aiPrefillJS(query), true); } catch (_) {} }
const $ = (id) => document.getElementById(id);
const viewsEl = $('views');
const tabsEl = $('tabs');
// AI assistant: a docked panel on the right. layoutViews() reserves its width.
const AI_PANEL_WIDTH = 400;
let aiOpen = false;
async function toggleAi(force) {
try { aiOpen = await window.materia.aiToggle(force); } catch (_) { aiOpen = false; }
const b = $('nav-ai'); if (b) b.classList.toggle('active', aiOpen);
try { layoutViews(); } catch (_) {}
}
try { const b = $('nav-ai'); if (b) b.addEventListener('click', () => toggleAi()); } catch (_) {}
const omni = $('omnibox');
// focusing the address bar must also pull OS keyboard focus to the chrome view (else it sits on the page view)
function focusOmni() { try { omni.focus(); } catch (_) {} try { window.materia.focusChrome(); } catch (_) {} }
/* ---------- workspaces (each has its own login partition) ---------- */
let workspaces = []; // [{id, name}]
let activeWsId = null;
let IS_SECONDARY = false; // a torn-off window: opens one URL, never persists its tab session
let tabs = []; // [{id, wsId, view, title, url, favicon, loading, groupId}]
let tabGroups = []; // [{id, wsId, name, color, collapsed}] - collapsible folders in the tab strip
const GROUP_COLORS = ['#f1cb53', '#4f93f2', '#e1554d', '#33d1bd', '#a96ff2', '#e0a93a'];
function wsGroups() { return tabGroups.filter(g => g.wsId === activeWsId); }
function loadTabGroups() { try { tabGroups = JSON.parse(localStorage.getItem('materia-tabgroups')) || []; } catch (_) { tabGroups = []; } }
let activeId = null; // currently shown tab (always inside activeWsId)
let splitId = null; // second pane in split view (null = single pane)
let activeTabByWs = {}; // remembers each workspace's last-active tab
let pendingByWs = {}; // restored-but-not-yet-loaded tabs, per workspace (lazy)
let seq = 0;
let closedTabs = []; // recently closed (url+wsId) for Ctrl+Shift+T
let dragTabId = null; // tab being drag-reordered
let dragWsId = null; // workspace being drag-reordered
const THEME_ACCENT = { materia: '#f1cb53', crimson: '#e1554d', cobalt: '#4f93f2', amethyst: '#a96ff2', obsidian: '#c2ced3' };
const MAX_WS = THEMES.length; // one workspace per built-in theme (5)
const MUTE_SVG = '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>';
const PENCIL_SVG = '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>';
const COPY_SVG = '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>';
function wsIndex(id) { const i = workspaces.findIndex(w => w.id === id); return i < 0 ? 0 : Math.min(MAX_WS - 1, i); }
function wsTheme(id) { const w = workspaces.find(x => x.id === id); return (w && THEMES.includes(w.theme)) ? w.theme : THEMES[wsIndex(id)]; }
function wsColor(id) { return THEME_ACCENT[wsTheme(id)] || '#f1cb53'; }
function freeTheme() { const used = new Set(workspaces.map(w => w.theme).filter(t => THEMES.includes(t))); return THEMES.find(t => !used.has(t)) || THEMES[0]; }
function normalizeWsThemes() { const used = new Set(); workspaces.forEach(w => { if (!THEMES.includes(w.theme) || used.has(w.theme)) w.theme = THEMES.find(t => !used.has(t)) || THEMES[0]; used.add(w.theme); }); }
function wsPartition(wsId) { return 'persist:ws-' + wsId; }
function activeTab() { return tabs.find(t => t.id === activeId); }
function chromeInputFocused() { const a = document.activeElement; return !!a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA' || a.tagName === 'SELECT'); }
function activeWs() { return workspaces.find(w => w.id === activeWsId); }
function wsTabs() { return tabs.filter(t => t.wsId === activeWsId); }
function ensureWs(wsId) { try { window.materia.ensurePartition(wsPartition(wsId)); } catch (_) {} }
function loadWorkspaces() {
try { workspaces = JSON.parse(localStorage.getItem('materia-workspaces')) || []; } catch (_) { workspaces = []; }
if (!workspaces.length) workspaces = [{ id: 'default', name: 'Personal' }];
activeWsId = localStorage.getItem('materia-active-ws');
if (!workspaces.some(w => w.id === activeWsId)) activeWsId = workspaces[0].id;
normalizeWsThemes(); // ensure each workspace has a unique color from the 5-theme pool
}
function saveWorkspaces() {
localStorage.setItem('materia-workspaces', JSON.stringify(workspaces));
localStorage.setItem('materia-active-ws', activeWsId);
}
let _saveTimer = null;
function saveSession() { if (IS_SECONDARY) return; clearTimeout(_saveTimer); _saveTimer = setTimeout(_doSave, 400); }
function _doSave() {
const live = tabs.map(t => ({ wsId: t.wsId, url: isNewtab(t.url) ? '' : t.url, active: activeTabByWs[t.wsId] === t.id, pinned: !!t.pinned, groupId: t.groupId || null, noSleep: !!t.noSleep }));
const pend = [];
Object.keys(pendingByWs).forEach(ws => pendingByWs[ws].forEach(s => pend.push({ wsId: ws, url: s.url, active: s.active, pinned: s.pinned, groupId: s.groupId || null, noSleep: s.noSleep })));
try { localStorage.setItem('materia-tabs', JSON.stringify(live.concat(pend))); } catch (_) {}
try { localStorage.setItem('materia-tabgroups', JSON.stringify(tabGroups)); } catch (_) {}
}
function restoreSession() {
loadTabGroups();
let saved = [];
try { saved = JSON.parse(localStorage.getItem('materia-tabs')) || []; } catch (_) {}
if (!saved.length) return false;
const byWs = {};
saved.forEach(s => { if (workspaces.some(w => w.id === s.wsId)) (byWs[s.wsId] = byWs[s.wsId] || []).push(s); });
let activeTabId = null;
(byWs[activeWsId] || []).forEach(s => { const t = makeTab(activeWsId, s.url, s.pinned); if (s.groupId) t.groupId = s.groupId; if (s.noSleep) t.noSleep = true; if (s.active) activeTabId = t.id; });
delete byWs[activeWsId];
pendingByWs = byWs;
const mine = tabs.filter(t => t.wsId === activeWsId);
if (!mine.length) return false;
activateTab((activeTabId && mine.some(t => t.id === activeTabId)) ? activeTabId : mine[mine.length - 1].id);
renderTabs();
return true;
}
/* ---------- URL helpers ---------- */
function isNewtab(url) { return !url || url.includes('newtab.html') || url === 'about:blank'; }
function prettyUrl(url) { return isNewtab(url) ? '' : url; }
/* ---------- tabs ---------- */
// ---- WebContentsView proxy: a tab's `view` looks like the old <webview> but drives a main-owned view over IPC ----
const viewState = {}; // vid -> { url, canBack, canForward } (cached so canGoBack/getURL stay synchronous)
function makeViewProxy(vid) {
const L = {}; // event name -> [listeners]
return {
_vid: vid, _L: L,
addEventListener: (ev, fn) => { (L[ev] = L[ev] || []).push(fn); },
_emit: (ev, payload) => { (L[ev] || []).forEach(fn => { try { fn(payload); } catch (_) {} }); },
loadURL: (u) => window.materia.viewNav({ vid: vid, action: 'load', url: u }),
reload: () => window.materia.viewNav({ vid: vid, action: 'reload' }),
goBack: () => window.materia.viewNav({ vid: vid, action: 'back' }),
goForward: () => window.materia.viewNav({ vid: vid, action: 'forward' }),
canGoBack: () => !!(viewState[vid] && viewState[vid].canBack),
canGoForward: () => !!(viewState[vid] && viewState[vid].canForward),
getURL: () => (viewState[vid] ? viewState[vid].url : ''),
setZoomFactor: (f) => window.materia.viewZoom({ vid: vid, factor: f }),
setAudioMuted: (m) => window.materia.viewMute({ vid: vid, muted: m }),
findInPage: (t, o) => window.materia.viewFind({ vid: vid, action: 'find', text: t, opts: o }),
stopFindInPage: (a) => window.materia.viewFind({ vid: vid, action: 'stop', arg: a }),
print: () => window.materia.viewPrint({ vid: vid }),
insertCSS: (css) => { window.materia.viewCss({ vid: vid, css: css }); return Promise.resolve(); },
executeJavaScript: (js, ug) => window.materia.viewExec({ vid: vid, js: js, userGesture: ug }).catch(() => null),
blur: () => {},
remove: () => { window.materia.viewDestroy({ vid: vid }); delete viewState[vid]; }
};
}
window.materia.onViewEvent((d) => {
const tab = tabs.find(t => t.id === d.vid); if (!tab || !tab.view || !tab.view._emit) return;
const p = d.payload || {};
if (d.event === 'did-navigate' || d.event === 'did-navigate-in-page') {
viewState[d.vid] = viewState[d.vid] || {};
viewState[d.vid].url = p.url; viewState[d.vid].canBack = p.canBack; viewState[d.vid].canForward = p.canForward;
tab.view._emit(d.event, {});
} else if (d.event === 'page-title-updated') tab.view._emit(d.event, { title: p.title });
else if (d.event === 'page-favicon-updated') tab.view._emit(d.event, { favicons: p.favicons });
else if (d.event === 'found-in-page') tab.view._emit(d.event, { result: p.result });
else tab.view._emit(d.event, {});
});
function makeTab(wsId, url, pinned) {
const target = url || newtabUrl();
ensureWs(wsId);
const id = ++seq;
const tab = { id, wsId, title: 'New Tab', url: target, favicon: null, loading: false, pinned: !!pinned, lastActive: Date.now(), asleep: false, audible: false, groupId: null, noSleep: false };
viewState[id] = { url: target, canBack: false, canForward: false };
tab.view = makeViewProxy(id);
window.materia.viewCreate({ vid: id, wsId: wsId, partition: wsPartition(wsId), url: target });
tabs.push(tab);
wireView(tab);
return tab;
}
function createTab(url) {
const t = makeTab(activeWsId, url);
if (isNewtab(t.url)) t.focusOnReady = true; // land the cursor in the address bar
renderTabs();
activateTab(t.id);
return t;
}
function activateTab(id) {
const t = tabs.find(x => x.id === id);
if (!t) return;
if (t.asleep) wakeTab(t); // recreate its view before showing it
t.lastActive = Date.now();
activeId = id;
activeTabByWs[t.wsId] = id;
if (splitId === id) splitId = null; // a tab can't be both panes
layoutViews();
renderTabs();
omni.value = prettyUrl(t.url);
updateChrome(t);
if (!splitId && isNewtab(t.url)) focusOmni(); // new tab → cursor in the address bar
saveSession();
}
function closeTab(id) {
const i = tabs.findIndex(t => t.id === id);
if (i === -1) return;
const ct = tabs[i]; const wsId = ct.wsId;
if (!isNewtab(ct.url)) { closedTabs.push({ url: ct.url, wsId: ct.wsId, pinned: !!ct.pinned }); if (closedTabs.length > 25) closedTabs.shift(); }
ct.view.remove();
tabs.splice(i, 1);
if (id === splitId) { splitId = null; layoutViews(); }
if (activeId !== id) { renderTabs(); saveSession(); return; }
const siblings = tabs.filter(x => x.wsId === wsId);
if (siblings.length) activateTab(siblings[siblings.length - 1].id);
else createTab();
saveSession();
}
function newXfer() { return 'xf_' + Date.now() + '_' + Math.floor(Math.random() * 1e6); }
// remove a tab from THIS window WITHOUT destroying its view — the live view is being moved to another window
function detachTab(id) {
const i = tabs.findIndex(t => t.id === id);
if (i === -1) return;
const ct = tabs[i]; const wsId = ct.wsId;
delete viewState[id];
tabs.splice(i, 1);
if (id === splitId) { splitId = null; layoutViews(); }
if (activeId === id) {
const siblings = tabs.filter(x => x.wsId === wsId);
if (siblings.length) activateTab(siblings[siblings.length - 1].id);
else if (IS_SECONDARY) { try { window.materia.winClose(); } catch (_) {} return; } // emptied a torn window → close it
else createTab();
}
renderTabs(); saveSession();
}
// build a tab around a view that is ALREADY alive in main (moved from another window) — no viewCreate, no reload
function adoptTab(o) {
o = o || {};
const wsId = activeWsId; // land it in the window's current workspace so it's visible (new windows already set activeWsId to the source's)
ensureWs(wsId);
const id = ++seq; const url = o.url || '';
const tab = { id, wsId, title: o.title || 'Tab', url: url, favicon: null, loading: false, pinned: false };
viewState[id] = { url: url, canBack: false, canForward: false };
tab.view = makeViewProxy(id);
tabs.push(tab);
wireView(tab);
window.materia.viewAdopt({ xfer: o.xfer, vid: id }); // main re-parents the live WebContentsView under this vid
renderTabs(); activateTab(id); saveSession();
return tab;
}
function makeTabEl(t) {
const el = document.createElement('div');
el.className = 'tab' + (t.id === activeId ? ' active' : '') + (t.id === splitId ? ' split-mate' : '') + (t.pinned ? ' pinned' : '') + (t.asleep ? ' asleep' : '') + (t.noSleep ? ' keep-awake' : '');
el.title = t.noSleep ? (t.title + ' (kept awake)') : t.title;
const fav = document.createElement('img');
fav.className = 'tab-fav' + (t.favicon ? '' : ' placeholder');
if (t.favicon) fav.src = t.favicon;
el.appendChild(fav);
if (t.muted) { const mu = document.createElement('span'); mu.className = 'tab-mute'; mu.innerHTML = MUTE_SVG; el.appendChild(mu); }
if (!t.pinned) {
const title = document.createElement('span');
title.className = 'tab-title';
title.textContent = t.loading ? 'Loading…' : (t.title || 'New Tab');
const close = document.createElement('button');
close.className = 'tab-close'; close.textContent = '✕';
close.addEventListener('click', (e) => { e.stopPropagation(); closeTab(t.id); });
el.append(title, close);
}
el.draggable = true;
el.addEventListener('click', () => activateTab(t.id));
el.addEventListener('auxclick', (e) => { if (e.button === 1) closeTab(t.id); });
el.addEventListener('contextmenu', (e) => { e.preventDefault(); e.stopPropagation(); showTabMenu(t, e.clientX, e.clientY); });
el.addEventListener('dragstart', (e) => { if (t.asleep) wakeTab(t); dragTabId = t.id; el.classList.add('dragging'); document.body.classList.add('tab-dragging'); applyChrome(); try { e.dataTransfer.effectAllowed = 'move'; } catch (_) {} });
el.addEventListener('dragend', (e) => {
el.classList.remove('dragging'); document.body.classList.remove('tab-dragging'); const torn = dragTabId; dragTabId = null; applyChrome();
// dropped outside this window's bounds → tear the tab into its own window
if (torn === t.id && (e.screenX || e.screenY)) {
const out = e.screenX < window.screenX || e.screenX > window.screenX + window.outerWidth || e.screenY < window.screenY || e.screenY > window.screenY + window.outerHeight;
if (out) { try { window.materia.tabMoveOut({ vid: t.id, xfer: newXfer(), url: t.url, title: t.title, wsId: t.wsId, x: e.screenX, y: e.screenY }); } catch (_) {} detachTab(t.id); }
}
});
el.addEventListener('dragover', (e) => { if (dragTabId && dragTabId !== t.id) { e.preventDefault(); el.classList.add('tab-drop'); } });
el.addEventListener('dragleave', () => el.classList.remove('tab-drop'));
el.addEventListener('drop', (e) => { e.preventDefault(); el.classList.remove('tab-drop'); if (dragTabId && dragTabId !== t.id) { const dt = tabs.find(x => x.id === dragTabId); if (dt && !dt.pinned) dt.groupId = t.groupId || null; reorderTab(dragTabId, t.id); } dragTabId = null; });
return el;
}
function makeGroupChip(g, count) {
const chip = document.createElement('div');
chip.className = 'tab-group-chip' + (g.collapsed ? ' collapsed' : '');
chip.dataset.gid = g.id;
chip.style.setProperty('--grp', g.color || '#f1cb53');
chip.title = g.name;
const dot = document.createElement('span'); dot.className = 'tgc-dot'; chip.appendChild(dot);
const nm = document.createElement('span'); nm.className = 'tgc-name'; nm.textContent = g.collapsed ? (g.name + ' · ' + count) : g.name; chip.appendChild(nm);
chip.addEventListener('click', () => { g.collapsed = !g.collapsed; renderTabs(); saveSession(); });
chip.addEventListener('contextmenu', (e) => { e.preventDefault(); e.stopPropagation(); showGroupMenu(g, e.clientX, e.clientY); });
chip.addEventListener('dragover', (e) => { if (dragTabId) { e.preventDefault(); chip.classList.add('tab-drop'); } });
chip.addEventListener('dragleave', () => chip.classList.remove('tab-drop'));
chip.addEventListener('drop', (e) => { e.preventDefault(); chip.classList.remove('tab-drop'); const dt = dragTabId && tabs.find(x => x.id === dragTabId); if (dt && !dt.pinned) { dt.groupId = g.id; renderTabs(); saveSession(); } dragTabId = null; });
return chip;
}
function renderTabs() {
tabGroups = tabGroups.filter(g => tabs.some(t => t.groupId === g.id)); // drop groups with no tabs
tabsEl.innerHTML = '';
const all = wsTabs().slice();
all.filter(t => t.pinned).forEach(t => tabsEl.appendChild(makeTabEl(t)));
const unpinned = all.filter(t => !t.pinned);
const emitted = new Set();
unpinned.forEach(t => {
const g = t.groupId ? tabGroups.find(x => x.id === t.groupId && x.wsId === activeWsId) : null;
if (!g) { if (t.groupId) t.groupId = null; tabsEl.appendChild(makeTabEl(t)); return; }
if (emitted.has(g.id)) return;
emitted.add(g.id);
const members = unpinned.filter(x => x.groupId === g.id);
tabsEl.appendChild(makeGroupChip(g, members.length));
if (!g.collapsed) members.forEach(m => { const el = makeTabEl(m); el.classList.add('grouped'); el.style.setProperty('--grp', g.color || '#f1cb53'); tabsEl.appendChild(el); });
});
}
function newGroupFromTab(t) {
const color = GROUP_COLORS[tabGroups.length % GROUP_COLORS.length];
const g = { id: 'g' + (++seq), wsId: activeWsId, name: 'New group', color: color, collapsed: false };
tabGroups.push(g); t.groupId = g.id;
renderTabs(); saveSession(); renameGroup(g);
}
function renameGroup(g) {
const chip = tabsEl.querySelector('.tab-group-chip[data-gid="' + g.id + '"]'); if (!chip) return;
const nm = chip.querySelector('.tgc-name'); if (!nm) return;
const inp = document.createElement('input'); inp.className = 'tgc-input'; inp.value = g.name; inp.maxLength = 24;
inp.addEventListener('click', (e) => e.stopPropagation());
nm.replaceWith(inp); inp.focus(); inp.select();
let done = false;
const finish = (keep) => { if (done) return; done = true; if (keep) g.name = inp.value.trim() || g.name; renderTabs(); saveSession(); };
inp.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); finish(true); } else if (e.key === 'Escape') { finish(false); } });
inp.addEventListener('blur', () => finish(true));
}
function showGroupMenu(g, x, y) {
showMenu([
{ label: g.collapsed ? 'Expand group' : 'Collapse group', fn: () => { g.collapsed = !g.collapsed; renderTabs(); saveSession(); } },
{ label: 'Rename group', fn: () => renameGroup(g) },
{ label: 'Change color', fn: () => { const i = GROUP_COLORS.indexOf(g.color); g.color = GROUP_COLORS[(i + 1) % GROUP_COLORS.length]; renderTabs(); saveSession(); } },
{ label: 'New tab in group', fn: () => { const t = createTab(); t.groupId = g.id; renderTabs(); saveSession(); } },
{ label: 'Ungroup tabs', fn: () => { wsTabs().forEach(t => { if (t.groupId === g.id) t.groupId = null; }); renderTabs(); saveSession(); } },
{ label: 'Close group', fn: () => { wsTabs().filter(t => t.groupId === g.id).map(t => t.id).forEach(closeTab); renderTabs(); saveSession(); } }
], x, y);
}
/* ---------- split view (two panes side by side in the same window) ---------- */
// The chrome is a transparent view sitting OVER the live page. Normally it's sized to just the toolbar strip,
// so the page below stays fully interactive. When any overlay/menu/dropdown opens we tell main to expand the
// chrome to the full window, so panels and menus float over the live page (which keeps playing) and nothing
// gets clipped — then shrink back to the strip when they close.
function isEditable(t) { return !!(t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)); }
function anyOverlayOpen() {
const shown = (id) => { const e = $(id); return !!(e && !e.classList.contains('hidden')); };
if (shown('settings') || shown('notes-panel') || shown('list-panel') || shown('findbar') || shown('ws-menu') || shown('palette') || shown('reader')) return true;
if (document.querySelector('.omni-suggest.open, .folder-pop.open, .soc-overflow.open, #ctx-menu, .confirm-ov')) return true;
if (isEditable(document.activeElement)) return true; // a chrome field (address bar, settings) is focused — chrome must be the top, focusable layer
return false;
}
function stripHeight() { try { return Math.max(1, Math.ceil(viewsEl.getBoundingClientRect().top)) || 92; } catch (_) { return 92; } }
let _chromeFull = null;
let _lastY = 9999; // last pointer Y inside the chrome; start in the content region so the chrome begins BEHIND the page
// The chrome floats ABOVE the page while the pointer is over the toolbar strip OR an overlay is open (so the
// address bar, menus and dropdowns are interactive and render over the page); it tucks BEHIND the page while
// the pointer is over the content (so the page is clickable). Because every menu/dropdown opens from a toolbar
// click, the chrome is already on top when it appears — no reorder mid-open, which would blur and dismiss it.
// While a tab is being dragged, keep the chrome on top across the whole window so its document-level
// dragover (which marks the window a valid move-target) suppresses the OS "no-drop" cursor everywhere —
// otherwise the cursor sits over the page view, which rejects the drag, and shows 🚫 even though releasing docks fine.
function desiredTop() { return dragTabId != null || anyOverlayOpen() || _lastY < stripHeight(); }
function applyChrome() {
const top = desiredTop();
if (top === _chromeFull) return;
_chromeFull = top;
try { window.materia.chromeBounds({ full: top }); } catch (_) {}
}
document.addEventListener('mousemove', (e) => { _lastY = e.clientY; applyChrome(); }, true);
function layoutViews() {
const _wa = tabs.find(t => t.id === activeId); if (_wa && _wa.asleep) wakeTab(_wa); // never position a slept view
const _ws = splitId && tabs.find(t => t.id === splitId); if (_ws && _ws.asleep) wakeTab(_ws);
if (splitId && !tabs.some(t => t.id === splitId && t.wsId === activeWsId && t.id !== activeId)) splitId = null;
const on = !!splitId;
const r = viewsEl.getBoundingClientRect();
const X = r.left, Y = r.top, H = r.height;
const aiW = aiOpen ? Math.min(AI_PANEL_WIDTH, Math.floor(r.width * 0.5)) : 0;
const W = r.width - aiW; // shrink the content area when the AI panel is docked
const halfW = Math.round(W / 2);
tabs.forEach(t => {
const left = t.id === activeId, right = on && t.id === splitId;
if (on && left) window.materia.viewBounds({ vid: t.id, x: X, y: Y, width: halfW, height: H });
else if (right) window.materia.viewBounds({ vid: t.id, x: X + halfW, y: Y, width: W - halfW, height: H });
else if (!on && left) window.materia.viewBounds({ vid: t.id, x: X, y: Y, width: W, height: H });
else window.materia.viewHide({ vid: t.id });
});
if (aiW) window.materia.aiPanelBounds({ x: X + W, y: Y, width: aiW, height: H });
else window.materia.aiPanelHide();
try { window.materia.aiActiveTab(activeId); } catch (_) {} // keep main's active-tab pointer in sync for the AI
try { document.documentElement.style.setProperty('--mm-ai-dock', aiW + 'px'); } catch (_) {} // overlays reserve the dock
applyChrome();
}
window.addEventListener('resize', () => { try { layoutViews(); } catch (_) {} });
{ let _vt = null; const obs = new MutationObserver(() => { clearTimeout(_vt); _vt = setTimeout(() => { try { applyChrome(); } catch (_) {} }, 16); }); obs.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'style'] }); }
// focusing a chrome field must float the chrome above the page AND grab OS keyboard focus, or typing goes to the page
document.addEventListener('focusin', (e) => { try { applyChrome(); } catch (_) {} if (isEditable(e.target)) { try { window.materia.focusChrome(); } catch (_) {} } });
document.addEventListener('focusout', () => { setTimeout(() => { try { applyChrome(); } catch (_) {} }, 0); });
function openInSplit(id) {
if (id === activeId || !tabs.some(t => t.id === id && t.wsId === activeWsId)) {
const t = makeTab(activeWsId, null); // spawn a fresh tab for the second pane
splitId = t.id;
} else {
splitId = id;
}
layoutViews(); renderTabs(); saveSession();
}
function exitSplit() { splitId = null; layoutViews(); renderTabs(); }
/* ---------- tab pinning + generic right-click menu ---------- */
function togglePin(t) { t.pinned = !t.pinned; renderTabs(); saveSession(); }
/* ---------- RAM saver: sleep idle background tabs (free the renderer, reload on click) ---------- */
let ramSaver = (localStorage.getItem('materia-ramsaver') || '1') === '1'; // default ON
let sleepAfterMin = parseInt(localStorage.getItem('materia-sleep-min') || '15', 10) || 15;
let sleepTimer = null;
function sleepEligible(t) {
return t && !t.asleep && t.id !== activeId && t.id !== splitId && !t.pinned && !t.noSleep && !t.audible && !isNewtab(t.url) && !t.loading;
}
function toggleNoSleep(t) { t.noSleep = !t.noSleep; if (t.noSleep && t.asleep) wakeTab(t); renderTabs(); saveSession(); }
function sleepTab(t) {
if (!sleepEligible(t)) return;
t._wakeUrl = (t.view && t.view.getURL && t.view.getURL()) || t.url;
t.asleep = true;
try { window.materia.viewDestroy({ vid: t.id }); } catch (_) {} // frees the tab's renderer process
if (viewState[t.id]) viewState[t.id].url = t._wakeUrl; // keep url so getURL stays correct while asleep
renderTabs();
}
function wakeTab(t) {
if (!t || !t.asleep) return;
t.asleep = false;
const url = t._wakeUrl || t.url || newtabUrl();
viewState[t.id] = { url, canBack: false, canForward: false };
try { window.materia.viewCreate({ vid: t.id, wsId: t.wsId, partition: wsPartition(t.wsId), url: url }); } catch (_) {}
t.lastActive = Date.now();
renderTabs();
}
function sleepSweep() {
if (!ramSaver) return;
const now = Date.now(), cutoff = Math.max(1, sleepAfterMin) * 60000;
tabs.forEach((t) => {
if (!sleepEligible(t)) return;
if (!t.lastActive) { t.lastActive = now; return; }
if (now - t.lastActive > cutoff) sleepTab(t);
});
}
function startSleepSweep() {
if (sleepTimer) { clearInterval(sleepTimer); sleepTimer = null; }
if (ramSaver) sleepTimer = setInterval(sleepSweep, 60000);
}
startSleepSweep();
function renderPerf() {
const t = $('toggle-ramsaver'); if (t) t.checked = ramSaver;
const s = $('sleep-after'); if (s) s.value = String(sleepAfterMin);
}
{ const t = $('toggle-ramsaver'); if (t) t.addEventListener('change', () => { ramSaver = !!t.checked; localStorage.setItem('materia-ramsaver', ramSaver ? '1' : '0'); startSleepSweep(); }); }
{ const s = $('sleep-after'); if (s) s.addEventListener('change', () => { sleepAfterMin = parseInt(s.value, 10) || 15; localStorage.setItem('materia-sleep-min', String(sleepAfterMin)); }); }
function closeCtxMenu() { const e = $('ctx-menu'); if (e) e.remove(); }
function showMenu(items, x, y) {
closeCtxMenu();
const m = document.createElement('div'); m.className = 'ctx-menu'; m.id = 'ctx-menu';
items.forEach((it) => { const b = document.createElement('button'); b.className = 'ctx-item'; b.textContent = it.label; b.addEventListener('click', () => { closeCtxMenu(); it.fn(); }); m.appendChild(b); });
document.body.appendChild(m);
m.style.left = Math.min(x, window.innerWidth - 200) + 'px';
m.style.top = Math.min(y, window.innerHeight - 30 - items.length * 36) + 'px';
}
function showTabMenu(t, x, y) {
const items = [
{ label: t.pinned ? 'Unpin tab' : 'Pin tab', fn: () => togglePin(t) },
{ label: t.muted ? 'Unmute tab' : 'Mute tab', fn: () => toggleMute(t) },
{ label: t.noSleep ? 'Allow sleeping' : 'Keep awake (never sleep)', fn: () => toggleNoSleep(t) },
{ label: splitId ? 'Open in split (replace pane)' : 'Open in split view', fn: () => openInSplit(t.id) }
];
if (splitId) items.push({ label: 'Exit split view', fn: exitSplit });
if (!t.pinned) {
if (t.groupId) items.push({ label: 'Remove from group', fn: () => { t.groupId = null; renderTabs(); saveSession(); } });
else {
items.push({ label: 'Add tab to new group', fn: () => newGroupFromTab(t) });
wsGroups().forEach(g => items.push({ label: 'Add to group: ' + g.name, fn: () => { t.groupId = g.id; renderTabs(); saveSession(); } }));
}
}
items.push(
{ label: 'New tab', fn: () => createTab() },
{ label: 'Duplicate tab', fn: () => createTab(t.url) },
{ label: 'Move to new window', fn: () => { try { window.materia.tabMoveOut({ vid: t.id, xfer: newXfer(), url: t.url, title: t.title, wsId: t.wsId }); } catch (_) {} detachTab(t.id); } },
{ label: 'Reload', fn: () => { try { t.view.reload(); } catch (_) {} } },
{ label: 'Close tab', fn: () => closeTab(t.id) },
{ label: 'Close other tabs', fn: () => { wsTabs().filter(x => x.id !== t.id && !x.pinned).map(x => x.id).forEach(closeTab); } }
);
showMenu(items, x, y);
}
/* ---------- per-tab webview events ---------- */
function wireView(tab) {
const v = tab.view;
v.addEventListener('page-title-updated', (e) => { tab.title = e.title; renderTabs(); });
v.addEventListener('page-favicon-updated', (e) => { tab.favicon = (e.favicons && e.favicons[0]) || null; renderTabs(); });
v.addEventListener('did-start-loading', () => { tab.loading = true; renderTabs(); if (tab.id === activeId) setLoad(true); });
v.addEventListener('did-stop-loading', () => { tab.loading = false; renderTabs(); if (tab.id === activeId) setLoad(false); addHistory(tab.url, tab.title); if (tab._pendingAI != null) { const q = tab._pendingAI; tab._pendingAI = null; if (q) injectAIPrefill(v, q); } });
const onNav = () => {
tab.url = v.getURL();
if (tab.id === activeId) { omni.value = prettyUrl(tab.url); updateChrome(tab); }
saveSession();
};
v.addEventListener('did-navigate', onNav);
v.addEventListener('did-navigate-in-page', onNav);
v.addEventListener('media-started-playing', () => { tab.audible = true; }); // RAM-saver skips audible tabs
v.addEventListener('media-paused', () => { tab.audible = false; });
v.addEventListener('found-in-page', (e) => {
if (tab.id !== activeId) return;
const r = e.result || {}; const c = $('find-count');
if (c) c.textContent = r.matches ? (r.activeMatchOrdinal + ' / ' + r.matches) : 'No matches';
});
v.addEventListener('dom-ready', () => {
try { v.setZoomFactor(effectiveZoom()); } catch (_) {}
if (isNewtab(tab.url)) { try { v.executeJavaScript('window.__setTheme&&window.__setTheme(' + JSON.stringify(currentTheme) + ')', true); } catch (_) {} }
if (tab.focusOnReady) { tab.focusOnReady = false; focusOmni(); } // new tab → cursor in the address bar
if (forceRightClick) { try { v.executeJavaScript(UNBLOCK_JS, true); } catch (_) {} }
if (!isNewtab(tab.url)) { try { window.materia.getCosmetics(tab.url).then(css => { if (css) v.insertCSS(css).catch(() => {}); }).catch(() => {}); } catch (_) {} }
});
}
function updateChrome(tab) {
const v = tab.view;
try { $('nav-back').disabled = !v.canGoBack(); $('nav-fwd').disabled = !v.canGoForward(); } catch (_) {}
const secure = /^https:/.test(tab.url || '');
const lk = $('omni-lock');
if (isNewtab(tab.url)) { lk.innerHTML = OMNI_ICONS.search; lk.style.color = ''; }
else if (secure) { lk.innerHTML = OMNI_ICONS.lock; lk.style.color = ''; }
else { lk.innerHTML = OMNI_ICONS.warn; lk.style.color = '#e8a13a'; }
updateStar();
}
function setLoad(on) {
const bar = $('loadbar');
if (on) { bar.classList.add('on'); bar.style.width = '12%'; setTimeout(() => { if (bar.classList.contains('on')) bar.style.width = '78%'; }, 220); }
else { bar.style.width = '100%'; setTimeout(() => { bar.classList.remove('on'); bar.style.width = '0'; }, 280); }
}
/* ---------- navigation / omnibox ---------- */
const OMNI_PROVIDERS = {
ddg: { name: 'DuckDuckGo', url: 'https://duckduckgo.com/?q=%s&kp=-2' },
startpage: { name: 'Startpage', url: 'https://www.startpage.com/sp/search?query=%s' },
brave: { name: 'Brave', url: 'https://search.brave.com/search?q=%s' },
google: { name: 'Google', url: 'https://www.google.com/search?q=%s' },
bing: { name: 'Bing', url: 'https://www.bing.com/search?q=%s' },
chatgpt: { name: 'ChatGPT', url: 'https://chatgpt.com/?q=%s' },
claude: { name: 'Claude', url: 'https://claude.ai/new?q=%s' },
gemini: { name: 'Gemini', url: 'https://gemini.google.com/app?q=%s' },
grok: { name: 'Grok', url: 'https://grok.com/?q=%s' },
perplexity: { name: 'Perplexity', url: 'https://www.perplexity.ai/search?q=%s' }
};
const OMNI_BANGS = {
g: 'https://www.google.com/search?q=%s', ddg: 'https://duckduckgo.com/?q=%s', bing: 'https://www.bing.com/search?q=%s',
yt: 'https://www.youtube.com/results?search_query=%s', w: 'https://en.wikipedia.org/wiki/Special:Search?search=%s',
gh: 'https://github.com/search?q=%s&type=repositories', r: 'https://www.reddit.com/search/?q=%s',
x: 'https://x.com/search?q=%s', tw: 'https://x.com/search?q=%s', a: 'https://www.amazon.com/s?k=%s',
maps: 'https://www.google.com/maps/search/%s', so: 'https://stackoverflow.com/search?q=%s',
npm: 'https://www.npmjs.com/search?q=%s', imdb: 'https://www.imdb.com/find/?q=%s',
img: 'https://duckduckgo.com/?q=%s&iax=images&ia=images', tr: 'https://translate.google.com/?sl=auto&tl=en&text=%s'
};
function omniProviderName() { let pid = 'ddg'; try { pid = window.materia.getProvider() || 'ddg'; } catch (_) {} return (OMNI_PROVIDERS[pid] || OMNI_PROVIDERS.ddg).name; }
function resolveQuery(text) {
text = (text || '').trim(); if (!text) return null;
if (text.charAt(0) === '!') { const sp = text.indexOf(' '); const bang = (sp < 0 ? text.slice(1) : text.slice(1, sp)).toLowerCase(); const rest = sp < 0 ? '' : text.slice(sp + 1).trim(); if (OMNI_BANGS[bang]) return OMNI_BANGS[bang].replace('%s', encodeURIComponent(rest)); }
if (/^(https?|file|about|data|view-source):/i.test(text)) return text;
if (!/\s/.test(text) && /^[^\s.]+\.[^\s.]{2,}/.test(text)) return 'https://' + text;
let pid = 'ddg'; try { pid = window.materia.getProvider() || 'ddg'; } catch (_) {}
return (OMNI_PROVIDERS[pid] || OMNI_PROVIDERS.ddg).url.replace('%s', encodeURIComponent(text));
}
function calcResult(text) {
const s = (text || '').trim();
if (s.length > 40 || !/^[-+/*().\d\s]+$/.test(s) || !/[-+*/]/.test(s)) return null;
try { const v = Function('"use strict";return (' + s + ')')(); if (typeof v === 'number' && isFinite(v)) return Math.round(v * 1e6) / 1e6; } catch (_) {}
return null;
}
function omniNavigate(text) { const url = resolveQuery(text); if (!url) return; const t = activeTab(); if (t) t.view.loadURL(url); else createTab(url); }
let suggItems = []; let suggSel = -1; let _suggTimer = null;
function hideSugg() { const b = $('omni-suggest'); if (b) { b.classList.remove('open'); b.innerHTML = ''; } suggItems = []; suggSel = -1; }
function renderSugg() {
const b = $('omni-suggest'); if (!b) return;
if (!suggItems.length) { hideSugg(); return; }
b.innerHTML = '';
suggItems.forEach((it, i) => {
const row = document.createElement('div'); row.className = 'sg-row' + (i === suggSel ? ' sel' : '');
const ic = document.createElement('span'); ic.className = 'sg-ic'; ic.textContent = it.type === 'calc' ? '=' : (it.type === 'go' ? '↵' : '\u{1F50E}');
const tx = document.createElement('span'); tx.className = 'sg-tx'; tx.textContent = it.label;
row.append(ic, tx);
row.addEventListener('mousedown', (e) => { e.preventDefault(); useSugg(i); });
b.appendChild(row);
});
b.classList.add('open');
}
function useSugg(i) {
const it = suggItems[i]; if (!it) return;
if (it.type === 'calc') { try { window.materia.copyText(String(it.value)); } catch (_) {} showMini('Copied ' + it.value); hideSugg(); return; }
omni.value = it.value; hideSugg(); omniNavigate(it.value); omni.blur();
}
function updateSugg() {
const text = omni.value;
if (!text.trim()) { hideSugg(); return; }
const items = [];
const c = calcResult(text); if (c !== null) items.push({ type: 'calc', label: text + ' = ' + c, value: c });
const isUrl = /^(https?|file|about|data):/i.test(text) || (!/\s/.test(text) && /^[^\s.]+\.[^\s.]{2,}/.test(text));
const isBang = text.charAt(0) === '!';
items.push({ type: 'go', label: isUrl ? ('Go to ' + text) : (isBang ? ('Bang · ' + text) : (omniProviderName() + ' · ' + text)), value: text });
suggItems = items; suggSel = -1; renderSugg();
if (isUrl || isBang) return;
const q = text;
window.materia.suggest(q).then(list => {
if (omni.value !== q) return;
(list || []).forEach(s => { if (s && s !== q && suggItems.length < 9) suggItems.push({ type: 'sugg', label: s, value: s }); });
renderSugg();
}).catch(() => {});
}
omni.addEventListener('input', () => { clearTimeout(_suggTimer); _suggTimer = setTimeout(updateSugg, 120); });
omni.addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown') { e.preventDefault(); if (suggItems.length) { suggSel = (suggSel + 1) % suggItems.length; renderSugg(); } }
else if (e.key === 'ArrowUp') { e.preventDefault(); if (suggItems.length) { suggSel = (suggSel - 1 + suggItems.length) % suggItems.length; renderSugg(); } }
else if (e.key === 'Enter') { e.preventDefault(); if (suggSel >= 0) useSugg(suggSel); else { hideSugg(); omniNavigate(omni.value); omni.blur(); } }
else if (e.key === 'Escape') { hideSugg(); omni.blur(); }
});
{ const wrap = $('omnibox-wrap'); if (wrap) wrap.addEventListener('mousedown', (e) => { if (e.target === wrap || e.target === $('omni-lock')) { e.preventDefault(); omni.focus(); } }); }
omni.addEventListener('focus', () => { $('omnibox-wrap').classList.add('focus'); omni.select(); });
// Any chrome form field that gains focus reclaims the keyboard from a focused <webview>
// (a guest page holding focus is what made the address bar refuse to type).
document.addEventListener('focusin', (e) => {
const tag = e.target && e.target.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
const t = activeTab(); if (t && t.view) { try { t.view.blur(); } catch (_) {} } // release the guest page's keyboard hold
try { window.materia.focusChrome(); } catch (_) {}
}
});
omni.addEventListener('blur', () => { $('omnibox-wrap').classList.remove('focus'); setTimeout(hideSugg, 150); const t = activeTab(); if (t) omni.value = prettyUrl(t.url); });
$('nav-back').addEventListener('click', () => { const t = activeTab(); if (t && t.view.canGoBack()) t.view.goBack(); });
$('nav-fwd').addEventListener('click', () => { const t = activeTab(); if (t && t.view.canGoForward()) t.view.goForward(); });
$('nav-reload').addEventListener('click', () => { const t = activeTab(); if (t) t.view.reload(); });
$('nav-home').addEventListener('click', () => { const t = activeTab(); if (t) t.view.loadURL(newtabUrl()); });
{ const b = $('nav-update'); if (b) b.addEventListener('click', async () => {
const page = b._url || 'https://github.com/marrowmyth/Materia-browser/releases/latest';
if (!window.materia.downloadUpdate) { createTab(page); return; }
const ok = await confirmModal('Download and install Slash ' + (b._ver ? 'v' + b._ver + ' ' : '') + 'now? It downloads here, then the installer opens to finish.', 'Update');
if (!ok) return;
showMini('Downloading update… 0%');
const r = await window.materia.downloadUpdate({});
if (!r || !r.ok) { showMini('Download failed — opening release page'); createTab(page); }
}); }
if (window.materia.onUpdateProgress) window.materia.onUpdateProgress((d) => {
if (!d) return;
if (d.done) showMini('Update downloaded — opening installer…');
else showMini('Downloading update… ' + (d.pct || 0) + '%');
});
if (window.materia.onUpdateAvailable) window.materia.onUpdateAvailable((d) => { const b = $('nav-update'); if (!b) return; b._url = (d && d.url) || 'https://github.com/marrowmyth/Materia-browser/releases/latest'; b._ver = (d && d.version) || ''; b.title = 'Update available — v' + ((d && d.version) || '') + ' · click to install'; b.classList.remove('hidden'); });
$('newtab').addEventListener('click', () => createTab());
/* ---------- video downloader (yt-dlp) ---------- */
function vdDownload(url, quality) {
url = (url || '').trim(); if (!/^https?:/i.test(url)) { showMini('Enter a valid video URL'); return; }
showMini('Starting video download…');
const st = $('vd-status'); if (st) st.textContent = 'Starting…';
window.materia.ytdlpDownload(url, quality || 'best').then(r => { if (!r || !r.ok) { showMini('yt-dlp: ' + ((r && r.error) || 'failed')); if (st) st.textContent = (r && r.error) || 'Failed'; } });
}
{ const b = $('vd-go'); if (b) b.addEventListener('click', () => vdDownload($('vd-url').value, ($('vd-quality') || {}).value || 'best')); }
{ const i = $('vd-url'); if (i) i.addEventListener('keydown', (e) => { if (e.key === 'Enter') vdDownload(i.value, ($('vd-quality') || {}).value || 'best'); }); }
window.materia.onYtdlp((d) => { if (d) vdDownload(d.url, d.quality); });
window.materia.onYtdlpProgress((p) => {
const st = $('vd-status');
const fid = 'yt-' + (p.id || 'v');
if (p.done) {
const fail = p.error || 'Failed — check the link';
if (st) st.textContent = p.ok ? '✓ Saved to your Videos folder' : fail;
if (window._dlShelf) window._dlShelf.update(fid, { name: 'Video download', state: p.ok ? 'done' : 'failed', pct: p.ok ? 100 : undefined });
} else {
if (st) st.textContent = p.line || 'Downloading…';
const patch = { name: 'Video download', state: 'progress' };
if (p.pct != null) patch.pct = p.pct;
if (window._dlShelf) window._dlShelf.update(fid, patch);
}
});
/* ---------- download shelf (small footer showing progress for file + video downloads) ---------- */
(function () {
const bar = $('dl-footer'); if (!bar) return;
const items = new Map(); // id -> { name, pct, state:'progress'|'done'|'failed', path, openable }
const visible = () => !bar.classList.contains('hidden');
function render() {
const was = visible();
bar.textContent = '';
if (!items.size) { bar.classList.add('hidden'); if (was) try { layoutViews(); } catch (_) {} return; }
items.forEach((it, id) => {
const row = document.createElement('div');
row.className = 'dl-row' + (it.state === 'done' ? ' done' : it.state === 'failed' ? ' failed' : '');
const ico = document.createElement('span'); ico.className = 'dl-ico';
ico.textContent = it.state === 'done' ? '✓' : it.state === 'failed' ? '✕' : '↓'; row.appendChild(ico);
const name = document.createElement('span'); name.className = 'dl-name'; name.textContent = it.name || 'Download'; name.title = it.name || ''; row.appendChild(name);
const bw = document.createElement('span'); bw.className = 'dl-bar';
if (it.state === 'progress') { const i = document.createElement('i'); i.style.width = (it.pct != null ? Math.max(2, Math.min(100, it.pct)) : 4) + '%'; bw.appendChild(i); }
else bw.style.visibility = 'hidden';
row.appendChild(bw);
const pc = document.createElement('span'); pc.className = 'dl-pct';
if (it.state === 'progress') pc.textContent = it.pct != null ? Math.round(it.pct) + '%' : '…';
else if (it.state === 'failed') pc.textContent = 'Failed';
else if (it.openable) {
const o = document.createElement('span'); o.className = 'dl-act'; o.textContent = 'Open'; o.onclick = () => { try { window.materia.openPath(it.path); } catch (_) {} }; pc.appendChild(o);
const f = document.createElement('span'); f.className = 'dl-act'; f.textContent = 'Folder'; f.onclick = () => { try { window.materia.showItem(it.path); } catch (_) {} }; pc.appendChild(f);
} else pc.textContent = '✓ Done';
row.appendChild(pc);
const x = document.createElement('span'); x.className = 'dl-x'; x.textContent = '×'; x.title = 'Dismiss'; x.onclick = () => { items.delete(id); render(); }; row.appendChild(x);
bar.appendChild(row);
});
bar.classList.remove('hidden');
if (!was) try { layoutViews(); } catch (_) {}
}
function autoClear(id, ms) { setTimeout(() => { const it = items.get(id); if (it && it.state !== 'progress') { items.delete(id); render(); } }, ms || 14000); }
// regular browser file downloads
window.materia.onDownload((d) => {
if (!d || !d.id) return;
const it = items.get(d.id) || {};
it.name = d.name || it.name || 'Download';
if (d.total > 0) it.pct = d.received / d.total * 100;
if (d.path) it.path = d.path;
if (d.state === 'completed') { it.state = 'done'; it.pct = 100; it.openable = !!it.path; }
else if (d.state === 'interrupted' || d.state === 'cancelled' || d.state === 'failed') it.state = 'failed';
else it.state = 'progress';
items.set(d.id, it);
render();
if (it.state !== 'progress') autoClear(d.id);
});
// the yt-dlp handler pushes video progress into the same shelf
window._dlShelf = {
update(id, patch) {
const it = items.get(id) || { name: 'Video download' };
if (patch.name != null) it.name = patch.name;
if (patch.pct != null) it.pct = patch.pct;
if (patch.state != null) it.state = patch.state;
if (patch.openable != null) it.openable = patch.openable;
items.set(id, it);
render();
if (it.state !== 'progress') autoClear(id);
}
};
})();
/* ---------- window controls ---------- */
$('w-min').addEventListener('click', () => window.materia.winMin());
$('w-max').addEventListener('click', () => window.materia.winMax());
$('w-close').addEventListener('click', () => window.materia.winClose());
/* ---------- workspace switcher ---------- */
function renderWsSwitcher() {
const w = activeWs();
const cur = $('ws-current'); if (cur) cur.title = 'Workspaces — current: ' + (w ? w.name : '—');
const orb = document.querySelector('#ws-current .ws-orb');
if (orb) { const c = wsColor(activeWsId); orb.style.background = c; orb.style.boxShadow = '0 0 9px ' + c + ', 0 0 3px ' + c; }
const menu = $('ws-menu');
menu.querySelectorAll('.ws-item').forEach(n => n.remove());
workspaces.forEach(ws => {
const item = document.createElement('button');
item.className = 'ws-item' + (ws.id === activeWsId ? ' active' : '');
const dot = document.createElement('span'); dot.className = 'ws-dot';
const c = wsColor(ws.id); dot.style.background = c; dot.style.boxShadow = '0 0 6px ' + c;
const nm = document.createElement('span'); nm.className = 'ws-item-name'; nm.textContent = ws.name; nm.title = ws.name + ' — drag to reorder';
item.append(dot, nm);
item.addEventListener('click', (e) => { e.stopPropagation(); switchWorkspace(ws.id); $('ws-menu').classList.add('hidden'); });
const edit = document.createElement('span'); edit.className = 'ws-edit'; edit.title = 'Rename'; edit.innerHTML = PENCIL_SVG;
edit.addEventListener('click', (e) => { e.stopPropagation(); startRenameWs(ws, nm); });
item.appendChild(edit);
const cp = document.createElement('span'); cp.className = 'ws-copy'; cp.title = 'Copy bookmarks & logins to another workspace'; cp.innerHTML = COPY_SVG;
cp.addEventListener('click', (e) => { e.stopPropagation(); showCopyWsMenu(ws, e.clientX, e.clientY); });
item.appendChild(cp);
item.draggable = true;
item.addEventListener('dragstart', (e) => { dragWsId = ws.id; item.classList.add('dragging'); try { e.dataTransfer.effectAllowed = 'move'; } catch (_) {} });
item.addEventListener('dragend', () => { dragWsId = null; item.classList.remove('dragging'); });
item.addEventListener('dragover', (e) => { if (dragWsId && dragWsId !== ws.id) { e.preventDefault(); item.classList.add('ws-drop'); } });
item.addEventListener('dragleave', () => item.classList.remove('ws-drop'));
item.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); item.classList.remove('ws-drop'); if (dragWsId && dragWsId !== ws.id) reorderWs(dragWsId, ws.id); dragWsId = null; });
if (workspaces.length > 1) {
const del = document.createElement('span'); del.className = 'ws-del'; del.textContent = '✕'; del.title = 'Remove workspace';
del.addEventListener('click', (e) => { e.stopPropagation(); removeWorkspace(ws.id); });
item.appendChild(del);
}
menu.insertBefore(item, $('ws-new-input'));
});
const nw = $('ws-new'); if (nw) nw.style.display = workspaces.length >= MAX_WS ? 'none' : '';
}
// copy a workspace's bookmarks + logins into another workspace as an independent copy
function copyWorkspaceData(fromId, toId) {
if (fromId === toId) return;
const target = workspaces.find(w => w.id === toId); if (!target) return;
const clone = JSON.parse(JSON.stringify(bookmarks[fromId] || [])); // deep clone → standalone
bookmarks[toId] = (bookmarks[toId] || []).concat(clone);
saveBookmarks(); if (toId === activeWsId) renderBookmarks();
showMini('Copying bookmarks & logins to “' + target.name + '”…');
ensureWs(toId);
window.materia.copyWorkspaceCookies(wsPartition(fromId), wsPartition(toId))
.then(r => showMini(r && r.ok ? ('Copied to “' + target.name + '” — now standalone') : 'Bookmarks copied; logins didn’t transfer'))
.catch(() => showMini('Bookmarks copied; logins didn’t transfer'));
}
function showCopyWsMenu(srcWs, x, y) {
const others = workspaces.filter(w => w.id !== srcWs.id);
if (!others.length) { showMini('Create another workspace to copy into'); return; }
showMenu(others.map(w => ({ label: 'Copy to “' + w.name + '”', fn: () => copyWorkspaceData(srcWs.id, w.id) })), x, y);
}
function switchWorkspace(id) {
if (!workspaces.some(w => w.id === id)) return;
activeWsId = id;
ensureWs(id);
saveWorkspaces();
applyTheme(wsTheme(id)); // set theme BEFORE any tab is created so its start page is tinted correctly
if (pendingByWs[id]) {
const list = pendingByWs[id]; delete pendingByWs[id];
let act = null;
list.forEach(s => { const t = makeTab(id, s.url, s.pinned); if (s.groupId) t.groupId = s.groupId; if (s.noSleep) t.noSleep = true; if (s.active) act = t.id; });
if (act) activeTabByWs[id] = act;
}
const mine = tabs.filter(t => t.wsId === id);
if (mine.length) {
const remembered = activeTabByWs[id];
activateTab((remembered && mine.some(t => t.id === remembered)) ? remembered : mine[mine.length - 1].id);
} else {
createTab();
}
renderWsSwitcher();
renderBookmarks();
saveSession();
}
function doCreateWorkspace(name) {
if (workspaces.length >= MAX_WS) { showMini('Up to ' + MAX_WS + ' workspaces'); hideNewInput(); $('ws-menu').classList.add('hidden'); return; }
const id = 'ws' + Date.now().toString(36) + Math.floor(Math.random() * 1000);
workspaces.push({ id, name: name, theme: freeTheme() }); // claim the first free color
saveWorkspaces();
hideNewInput();
$('ws-menu').classList.add('hidden');
switchWorkspace(id);
}
function confirmModal(message, okLabel) {
return new Promise((resolve) => {
closeCtxMenu();
const ov = document.createElement('div'); ov.className = 'confirm-ov';
const card = document.createElement('div'); card.className = 'confirm-card';
const msg = document.createElement('p'); msg.className = 'confirm-msg'; msg.textContent = message; card.appendChild(msg);
const row = document.createElement('div'); row.className = 'confirm-row';
const cancel = document.createElement('button'); cancel.className = 'action-btn'; cancel.textContent = 'Cancel';
const ok = document.createElement('button'); ok.className = 'action-btn' + (okLabel ? '' : ' action-danger'); ok.textContent = okLabel || 'Remove';
row.append(cancel, ok); card.appendChild(row); ov.appendChild(card); document.body.appendChild(ov);
const done = (v) => { ov.remove(); resolve(v); };
cancel.addEventListener('click', () => done(false));
ok.addEventListener('click', () => done(true));
ov.addEventListener('click', (e) => { if (e.target === ov) done(false); });
});
}
async function removeWorkspace(id) {
if (workspaces.length <= 1) return;
if (!(await confirmModal('Remove this workspace? Its open tabs close, but its saved logins stay on disk and return if you recreate it.'))) return;
tabs.filter(t => t.wsId === id).forEach(t => t.view.remove());
tabs = tabs.filter(t => t.wsId !== id);
delete activeTabByWs[id];
workspaces = workspaces.filter(w => w.id !== id);
if (activeWsId === id) { activeWsId = workspaces[0].id; saveWorkspaces(); switchWorkspace(workspaces[0].id); }
else { saveWorkspaces(); renderWsSwitcher(); }
saveSession();
}
function showNewInput() { const i = $('ws-new-input'); i.classList.remove('hidden'); $('ws-new').classList.add('hidden'); i.value = ''; setTimeout(() => i.focus(), 0); }
function hideNewInput() { $('ws-new-input').classList.add('hidden'); $('ws-new').classList.remove('hidden'); }
function reorderWs(fromId, toId) {
const from = workspaces.findIndex(w => w.id === fromId); if (from < 0) return;
const moved = workspaces.splice(from, 1)[0];
let to = workspaces.findIndex(w => w.id === toId); if (to < 0) to = workspaces.length;
workspaces.splice(to, 0, moved);
saveWorkspaces(); renderWsSwitcher();
}
function startRenameWs(ws, nmEl) {
const inp = document.createElement('input'); inp.className = 'ws-rename'; inp.value = ws.name; inp.maxLength = 24; inp.spellcheck = false;
nmEl.replaceWith(inp); setTimeout(() => { inp.focus(); inp.select(); }, 0);
let done = false;
const commit = () => { if (done) return; done = true; const v = inp.value.trim(); if (v) { ws.name = v; saveWorkspaces(); } renderWsSwitcher(); };
inp.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); commit(); } else if (e.key === 'Escape') { done = true; renderWsSwitcher(); } });
inp.addEventListener('blur', commit);
inp.addEventListener('click', (e) => e.stopPropagation());
}
$('ws-current').addEventListener('click', (e) => { e.stopPropagation(); $('ws-menu').classList.toggle('hidden'); });
$('ws-menu').addEventListener('click', (e) => e.stopPropagation());
$('ws-new').addEventListener('click', (e) => { e.stopPropagation(); showNewInput(); });
$('ws-new-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter') doCreateWorkspace((e.target.value.trim()) || ('Workspace ' + (workspaces.length + 1)));
else if (e.key === 'Escape') hideNewInput();
});
/* ---------- settings ---------- */
const settings = $('settings');
$('nav-settings').addEventListener('click', () => { settings.classList.remove('hidden'); collapseAllBlocks(); renderProviderSetting(); renderAdblockStatus(); renderTrusted(); renderDefaultBrowser(); renderAiSettings(); renderImport(); renderPasswordImport(); renderPerf(); });
function renderDefaultBrowser() {
const st = $('default-browser-status'); if (!st || !window.materia.defaultBrowserStatus) return;
window.materia.defaultBrowserStatus().then(s => {
if (!s || !s.supported) { st.textContent = 'Available on Windows.'; st.style.color = 'var(--ink-faint)'; return; }
if (!s.packaged) { st.textContent = 'Available in the installed app (not in dev mode).'; st.style.color = 'var(--ink-faint)'; return; }
st.textContent = s.isDefault ? '● Slash is your default browser.' : '○ Not currently the default.';
st.style.color = s.isDefault ? 'var(--teal)' : 'var(--ink-faint)';
}).catch(() => {});
}
{ const b = $('set-default-browser'); if (b) b.addEventListener('click', () => {
if (!window.materia.setDefaultBrowser) return;
window.materia.setDefaultBrowser().then(r => {
if (r && r.reason === 'dev') showMini('Works in the installed app — not in dev');
else if (r && r.reason === 'win-only') showMini('Windows only');
else showMini('In Default apps, pick “Slash Browser” for Web browser');
setTimeout(renderDefaultBrowser, 2000);
}).catch(() => {});
}); }
function renderTrusted() {
const list = $('trust-list'); if (!list || !window.materia.getTrusted) return;
window.materia.getTrusted().then(hosts => {
list.innerHTML = '';
if (!hosts.length) { const e = document.createElement('p'); e.className = 'set-note'; e.style.margin = '0'; e.textContent = 'No trusted sites yet.'; list.appendChild(e); return; }
hosts.sort().forEach(h => {
const row = document.createElement('div'); row.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px;padding:5px 10px;background:var(--bg);border:1px solid var(--line);border-radius:7px';
const name = document.createElement('span'); name.textContent = h; name.style.cssText = 'font-size:12.5px;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap';
const rm = document.createElement('button'); rm.className = 'iconbtn'; rm.textContent = '✕'; rm.title = 'Remove from trusted'; rm.style.flex = 'none';
rm.addEventListener('click', () => { window.materia.removeTrusted(h).then(renderTrusted); });
row.appendChild(name); row.appendChild(rm); list.appendChild(row);
});
});
}
function addTrustedFromInput() { const i = $('trust-input'); if (!i) return; const v = i.value.trim(); if (!v) return; window.materia.addTrusted(v).then(() => { i.value = ''; renderTrusted(); }); }
{ const b = $('trust-add'); if (b) b.addEventListener('click', addTrustedFromInput); const i = $('trust-input'); if (i) i.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); addTrustedFromInput(); } }); }
function renderAdblockStatus() {
const el = $('adblock-status'); if (!el || !window.materia.adblockStatus) return;
window.materia.adblockStatus().then(s => {
if (!s) return;
const map = { active: 'Active', loading: 'Loading filter lists…', failed: 'Failed to load lists — built-in tracker list still active' };
el.textContent = '● Adblocker: ' + (map[s.status] || s.status) + (s.status === 'active' ? ' · ' + (s.blocked || 0) + ' blocked this session' : '');
el.style.color = s.status === 'active' ? 'var(--teal)' : (s.status === 'failed' ? '#e8a13a' : 'var(--ink-faint)');
}).catch(() => {});
}
function renderProviderSetting() {
const sel = $('provider-select'); if (!sel) return;
let cur = 'ddg'; try { cur = window.materia.getProvider() || 'ddg'; } catch (_) {}
sel.innerHTML = '';
[['Search', ['ddg', 'startpage', 'brave', 'google', 'bing']], ['AI', ['chatgpt', 'claude', 'gemini', 'grok', 'perplexity']]].forEach(g => {
const og = document.createElement('optgroup'); og.label = g[0];
g[1].forEach(id => { const o = document.createElement('option'); o.value = id; o.textContent = (OMNI_PROVIDERS[id] || {}).name || id; if (id === cur) o.selected = true; og.appendChild(o); });
sel.appendChild(og);
});
}
{ const s = $('provider-select'); if (s) s.addEventListener('change', (e) => { try { window.materia.setProvider(e.target.value); } catch (_) {} }); }
$('settings-close').addEventListener('click', () => settings.classList.add('hidden'));
settings.addEventListener('click', (e) => { if (e.target === settings) settings.classList.add('hidden'); });
document.addEventListener('click', () => { $('ws-menu').classList.add('hidden'); hideNewInput(); closeCtxMenu(); if ($('soc-overflow')) $('soc-overflow').classList.remove('open'); if ($('folder-pop')) $('folder-pop').classList.remove('open'); if ($('folder-pop-2')) $('folder-pop-2').classList.remove('open'); });
// while a tab is being dragged, mark the whole window a valid move-target so the OS "no-drop" cursor never shows
document.addEventListener('dragover', (e) => { if (dragTabId != null) { e.preventDefault(); try { e.dataTransfer.dropEffect = 'move'; } catch (_) {} } });
// clicking into a page blurs the chrome (webview clicks don't bubble here) — close transient menus then too
window.addEventListener('blur', () => { closeCtxMenu(); $('ws-menu').classList.add('hidden'); if ($('soc-overflow')) $('soc-overflow').classList.remove('open'); if ($('folder-pop')) $('folder-pop').classList.remove('open'); if ($('folder-pop-2')) $('folder-pop-2').classList.remove('open'); });
window.materia.getSettings().then(s => {
$('toggle-trackers').checked = !!s.blockTrackers; updateShield(s.blockTrackers);
if ($('lang-select')) $('lang-select').value = s.language || 'en-US';
});
{ const ls = $('lang-select'); if (ls) ls.addEventListener('change', (e) => { window.materia.setLanguage(e.target.value); showMini('Language set — new pages will use it (restart to apply everywhere)'); }); }
$('toggle-trackers').addEventListener('change', (e) => { window.materia.setBlockTrackers(e.target.checked).then(updateShield); });
function updateShield(on) {
const s = $('omni-shield'); if (!s) return;
s.classList.remove('hidden'); s.classList.toggle('off', !on);
s.title = on ? 'Ad & tracker blocking ON — click to turn off' : 'Ad & tracker blocking OFF — click to turn on';
}
$('omni-shield').addEventListener('click', (e) => { e.stopPropagation(); const next = !$('toggle-trackers').checked; window.materia.setBlockTrackers(next).then(v => { $('toggle-trackers').checked = v; updateShield(v); }); });
/* color schemes */
function applyTheme(name) {
if (!THEMES.includes(name)) name = 'materia';
currentTheme = name;
if (name === 'materia') document.documentElement.removeAttribute('data-theme');
else document.documentElement.setAttribute('data-theme', name);
const w = activeWs(); if (w) { w.theme = name; saveWorkspaces(); } // theme is per-workspace
document.querySelectorAll('.swatch').forEach(s => s.classList.toggle('active', s.dataset.t === name));
renderWsSwitcher(); // re-tint the orb to this workspace's accent
tabs.forEach(t => { if (isNewtab(t.url)) { try { t.view.executeJavaScript('window.__setTheme && window.__setTheme(' + JSON.stringify(name) + ')', true); } catch (_) {} } });
}
$('theme-swatches').addEventListener('click', (e) => { const sw = e.target.closest('.swatch'); if (sw) applyTheme(sw.dataset.t); });
/* force right-click */
$('toggle-rightclick').checked = forceRightClick;
$('toggle-rightclick').addEventListener('change', (e) => {
forceRightClick = e.target.checked;
localStorage.setItem('materia-rightclick', forceRightClick ? '1' : '0');
});
/* clear data — targets the ACTIVE workspace's partition */
function flashStatus(msg) { const s = $('clear-status'); s.textContent = msg; s.classList.add('show'); setTimeout(() => s.classList.remove('show'), 2600); }
$('clear-keep').addEventListener('click', async () => { await window.materia.clearData(wsPartition(activeWsId), true); flashStatus('✓ Cleared — your logins in this workspace are intact.'); });
$('clear-all').addEventListener('click', async () => { await window.materia.clearData(wsPartition(activeWsId), false); flashStatus('✓ Everything cleared. Signed out of this workspace.'); });
/* ---------- popups & new-tab links ---------- */
// a link the user clicked: open a tab (foreground unless it was a ctrl/background click)