-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
1565 lines (1324 loc) · 62.6 KB
/
Copy pathrenderer.js
File metadata and controls
1565 lines (1324 loc) · 62.6 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 { ipcRenderer } = require('electron');
// Inline stroke icons, matching the set used by the in-page AI overlay.
const ICONS = {
open: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M13 5h6v6"/><path d="M19 5l-8 8"/><path d="M18.5 14.5V18a1.5 1.5 0 01-1.5 1.5H6A1.5 1.5 0 014.5 18V7A1.5 1.5 0 016 5.5h3.5"/></svg>',
pen: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M16.5 4.5l3 3L8 19l-4 1 1-4L16.5 4.5z"/><path d="M14.5 6.5l3 3"/></svg>',
trash: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M5 7h14"/><path d="M9.5 7V5.5h5V7"/><path d="M6.5 7l.8 12.2a1.3 1.3 0 001.3 1.3h6.8a1.3 1.3 0 001.3-1.3L17.5 7"/><path d="M10.5 11v6M13.5 11v6"/></svg>',
close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>',
globe: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17"/><path d="M12 3.5c2.2 2.4 3.3 5.3 3.3 8.5S14.2 18.1 12 20.5c-2.2-2.4-3.3-5.3-3.3-8.5S9.8 5.9 12 3.5z"/></svg>',
alert: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5"/><path d="M12 16.2v.2"/></svg>'
};
class MultiBrowserUI {
constructor() {
this.activeTabs = new Map(); // sessionId -> tab element
this.activeTabId = 'welcome';
this.sessions = new Map(); // sessionId -> session data
this.originalSessionNames = new Map(); // sessionId -> original user-defined name
this.modalOpen = false;
this.previousActiveTab = null;
this.availableLanguages = []; // spellchecker locales reported by Electron
this.defaultLanguages = ['pt-BR', 'en-US']; // default selection for new sessions
this.init();
}
init() {
this.setupEventListeners();
this.setupThemeSwitch();
this.loadTheme();
this.setupUpdates();
this.loadAvailableLanguages();
this.loadAppVersion();
this.loadSessions();
// Test if webview is supported
console.log('Webview support:', typeof document.createElement('webview'));
// Log any errors
window.addEventListener('error', (e) => {
console.error('Global error:', e.error);
});
// Listen for page title updates from main process
ipcRenderer.on('page-title-updated', (event, { sessionId, title, unreadCount }) => {
this.updateTabTitleWithUnreadCount(sessionId, title, unreadCount);
});
// Listen for favicon updates from main process
ipcRenderer.on('page-favicon-updated', (event, { sessionId, favicon }) => {
this.updateTabFavicon(sessionId, favicon);
});
// Generic status messages from the main process
ipcRenderer.on('app-message', (_e, { text, type }) => {
this.showNotification(text, type || 'info');
});
// Listen for external link notifications
ipcRenderer.on('external-link-opened', (event, { url }) => {
const domain = new URL(url).hostname;
this.showNotification(`Link opened in system browser: ${domain}`, 'info');
});
// Log any site notifications forwarded from main
ipcRenderer.on('site-notification', (_e, { sessionId, title, options, url }) => {
console.log(`[Site notification][${sessionId || 'unknown'}] ${title} | ${options?.body || ''} | ${url}`);
});
// Focus a specific session when a system notification is clicked
ipcRenderer.on('focus-session', async (_e, { sessionId, source }) => {
console.log(`🎯 Focus session request received: ${sessionId} (source: ${source || 'unknown'})`);
if (!sessionId) {
console.warn('No sessionId provided for focus-session');
return;
}
try {
// Check if session exists
const sessionData = this.sessions.get(sessionId);
if (!sessionData) {
console.warn(`Session ${sessionId} not found in active sessions`);
// Try to load sessions first
await this.loadSessions();
}
// Check if the tab is already open
if (this.activeTabs.has(sessionId)) {
console.log(`📑 Session ${sessionId} tab already open, switching to it`);
await this.switchToTab(sessionId);
} else {
console.log(`📑 Opening new tab for session ${sessionId}`);
await this.openSessionTab(sessionId);
await this.switchToTab(sessionId);
}
// Show a brief notification that we switched to the session
const sessionName = this.originalSessionNames.get(sessionId) || sessionData?.name || 'Unknown Session';
this.showNotification(`Switched to: ${sessionName}`, 'info');
console.log(`✅ Successfully focused session ${sessionId}`);
} catch (err) {
console.error('Failed to focus session from notification click:', err);
this.showNotification('Failed to switch to session', 'error');
}
});
// Handle download completion notifications
ipcRenderer.on('download-completed', (event, { sessionId, sessionName, fileName, filePath }) => {
console.log(`📥 Download completed in session ${sessionId} (${sessionName}): ${fileName}`);
const message = `File downloaded: ${fileName}`;
this.showNotification(message, 'success');
// Also log the full path for debugging
console.log(`📂 File saved to: ${filePath}`);
});
}
setupEventListeners() {
// Modal controls
const newTabBtn = document.getElementById('newTabBtn');
const createFirstSession = document.getElementById('createFirstSession');
const closeModal = document.getElementById('closeModal');
const cancelSession = document.getElementById('cancelSession');
const sessionModal = document.getElementById('sessionModal');
newTabBtn.addEventListener('click', async () => {
console.log('🔧 New Tab button clicked (tab bar)');
await this.showCreateSessionModal();
});
createFirstSession.addEventListener('click', async () => {
console.log('🔧 Create First Session button clicked (welcome)');
await this.showCreateSessionModal();
});
closeModal.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
console.log('🔧 Close modal button clicked');
await this.hideCreateSessionModal();
});
cancelSession.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
console.log('🔧 Cancel button clicked');
await this.hideCreateSessionModal();
});
// Welcome tab click handler
const welcomeTab = document.querySelector('.welcome-tab');
if (welcomeTab) {
welcomeTab.addEventListener('click', () => {
this.switchToTab('welcome');
});
}
// Close modal when clicking outside
sessionModal.addEventListener('click', async (e) => {
if (e.target === sessionModal) {
await this.hideCreateSessionModal();
}
});
// Form submission
const form = document.getElementById('createSessionForm');
form.addEventListener('submit', (e) => this.handleCreateSession(e));
// ESC key to close modal
document.addEventListener('keydown', async (e) => {
if (e.key === 'Escape' && sessionModal.classList.contains('show')) {
await this.hideCreateSessionModal();
}
});
// Setup rename modal
this.setupRenameModal();
// AI Settings modal
this.setupAISettingsModal();
}
async showCreateSessionModal() {
console.log('🔧 Attempting to show create session modal');
const modal = document.getElementById('sessionModal');
if (!modal) {
console.error('❌ Modal element not found!');
return;
}
// Store current active tab and hide browser view
this.previousActiveTab = this.activeTabId;
this.modalOpen = true;
console.log(`🔧 Current active tab: ${this.activeTabId}, storing as previous: ${this.previousActiveTab}`);
// Hide any active browser view to prevent it from covering the modal
if (this.activeTabId && this.activeTabId !== 'welcome') {
console.log('🔧 Hiding browser view before showing modal');
try {
await ipcRenderer.invoke('hide-browser-view', this.activeTabId);
} catch (error) {
console.log('Error hiding browser view:', error);
}
} else {
console.log('🔧 No browser view to hide (on welcome tab)');
}
console.log('✅ Modal element found, adding show class');
modal.classList.add('show');
// Force the modal to be on top with extreme z-index
modal.style.zIndex = '999999999';
modal.style.display = 'flex';
modal.style.position = 'fixed';
modal.style.top = '0';
modal.style.left = '0';
modal.style.width = '100vw';
modal.style.height = '100vh';
// New sessions default to PT + EN spellcheck (overridable per session).
this.populateLanguageSelect(document.getElementById('sessionLanguages'), this.defaultLanguages);
// Force all form inputs to be accessible
const nameInput = document.getElementById('sessionName');
const urlInput = document.getElementById('sessionUrl');
const allInputs = [nameInput, urlInput].filter(Boolean);
allInputs.forEach(input => {
// Keep the fields reachable above the browser view; appearance is
// left to the stylesheet.
input.style.cssText = `
z-index: 2147483647 !important;
pointer-events: all !important;
position: relative !important;
`;
input.disabled = false;
input.readOnly = false;
input.tabIndex = 0;
});
if (nameInput) {
setTimeout(() => {
nameInput.focus();
nameInput.select();
console.log('🔧 Input field focused and selected');
console.log('🔧 Input computed style:', window.getComputedStyle(nameInput).pointerEvents);
console.log('🔧 Input z-index:', window.getComputedStyle(nameInput).zIndex);
}, 200);
}
console.log('✅ Modal should now be visible with maximum z-index');
}
async hideCreateSessionModal() {
console.log('🔧 Hiding modal and restoring UI');
const modal = document.getElementById('sessionModal');
// Remove the show class and reset styles
modal.classList.remove('show');
modal.style.display = 'none';
modal.style.zIndex = '';
document.getElementById('createSessionForm').reset();
this.modalOpen = false;
// Restore the browser view if we had one active
console.log(`🔧 Previous active tab was: ${this.previousActiveTab}`);
if (this.previousActiveTab && this.previousActiveTab !== 'welcome') {
console.log('🔧 Restoring browser view after hiding modal');
try {
await ipcRenderer.invoke('show-browser-view', this.previousActiveTab);
console.log('✅ Browser view restored successfully');
} catch (error) {
console.log('Error restoring browser view:', error);
}
} else {
console.log('🔧 No browser view to restore (was on welcome tab)');
}
this.previousActiveTab = null;
console.log('✅ Modal hidden and UI restored');
}
async handleCreateSession(e) {
e.preventDefault();
const name = document.getElementById('sessionName').value.trim();
let url = document.getElementById('sessionUrl').value.trim();
if (!name) {
this.showNotification('Please enter a session name', 'error');
return;
}
// Validate and fix URL
if (url && !url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
if (!url) {
url = 'https://www.google.com';
}
try {
const spellLanguages = this.getSelectedLanguages(document.getElementById('sessionLanguages'));
const result = await ipcRenderer.invoke('create-browser-session', {
name,
url: url,
spellLanguages: spellLanguages.length ? spellLanguages : this.defaultLanguages
});
if (result.success) {
// Hide modal first
await this.hideCreateSessionModal();
// Show success notification
this.showNotification(`Session "${name}" created successfully!`, 'success');
// Refresh sessions list
await this.loadSessions();
// Open the new session tab
setTimeout(async () => {
await this.openSessionTab(result.sessionData);
}, 200);
} else {
this.showNotification(`Error: ${result.error}`, 'error');
}
} catch (error) {
this.showNotification(`Error creating session: ${error.message}`, 'error');
}
}
// ── Updates ──
// One row, four states: idle → available → downloading → ready to install.
setupUpdates() {
const row = document.getElementById('updateRow');
const action = document.getElementById('updateAction');
const manual = document.getElementById('updateManual');
if (!row || !action || !manual) return;
this.updateState = 'idle';
// Note the leading event arg: ipcRenderer.on hands the listener
// (event, payload), so destructuring the first parameter reads the
// event object and every field comes back undefined.
ipcRenderer.on('updates-progress', (_event, { percent, received, total }) => {
const fill = document.getElementById('updateBarFill');
const status = document.getElementById('updateStatus');
if (fill) fill.style.width = `${percent}%`;
if (status) {
const mb = (bytes) => (bytes / 1048576).toFixed(0);
status.textContent = total
? `${percent}% · ${mb(received)}/${mb(total)} MB`
: `${mb(received)} MB`;
}
});
action.addEventListener('click', () => this.runUpdateAction());
manual.addEventListener('click', () => ipcRenderer.invoke('updates-open-release'));
// Tab-bar badge: the only sign of an update while you are inside a
// session tab. Clicking it takes you to the row that does the work.
const badge = document.getElementById('updateBadge');
if (badge) {
badge.addEventListener('click', () => {
this.switchToTab('welcome');
row.classList.remove('attention');
void row.offsetWidth; // restart the animation
row.classList.add('attention');
row.scrollIntoView({ block: 'center', behavior: 'smooth' });
});
}
// Quiet check shortly after launch, then every 6 hours, so an update
// that lands while the app is open still gets noticed.
setTimeout(() => this.checkForUpdates({ silent: true }), 4000);
setInterval(() => {
// Don't interrupt a download or a pending install.
if (['downloading', 'installing', 'ready'].includes(this.updateState)) return;
this.checkForUpdates({ silent: true });
}, 6 * 60 * 60 * 1000);
}
showUpdateBadge(visible) {
const badge = document.getElementById('updateBadge');
if (badge) badge.hidden = !visible;
}
setUpdateUI({ status, button, state, progress = false, disabled = false, offerManual = false }) {
const row = document.getElementById('updateRow');
const statusEl = document.getElementById('updateStatus');
const actionEl = document.getElementById('updateAction');
const manualEl = document.getElementById('updateManual');
const barEl = document.getElementById('updateBar');
if (!row) return;
if (state) this.updateState = state;
statusEl.textContent = status;
barEl.hidden = !progress;
row.classList.toggle('downloading', progress);
actionEl.textContent = button;
actionEl.disabled = disabled;
manualEl.hidden = !offerManual;
row.classList.toggle('has-update', state === 'available' || state === 'ready');
row.classList.toggle('failed', state === 'error');
}
async runUpdateAction() {
if (this.updateState === 'available') return this.downloadUpdate();
if (this.updateState === 'ready') return this.installUpdate();
if (this.updateState === 'manual') return ipcRenderer.invoke('updates-open-release');
return this.checkForUpdates({ silent: false });
}
async checkForUpdates({ silent }) {
if (!silent) this.setUpdateUI({ status: 'Checking…', button: 'Check', disabled: true, state: 'checking' });
const result = await ipcRenderer.invoke('updates-check');
if (!result.success) {
if (silent) return;
this.setUpdateUI({
status: `Check failed: ${result.error}`,
button: 'Retry',
state: 'error',
offerManual: true
});
return;
}
if (!result.available) {
this.showUpdateBadge(false);
if (silent) return;
this.setUpdateUI({ status: `Up to date · v${result.currentVersion}`, button: 'Check', state: 'idle' });
return;
}
this.showUpdateBadge(true);
if (silent && this.activeTabId !== 'welcome') {
this.showNotification(`Update available: v${result.latestVersion}`, 'info');
}
if (!result.installable) {
// dev build, or no artifact for this platform — point at the release.
this.setUpdateUI({ status: `v${result.latestVersion} available`, button: 'View', state: 'manual' });
return;
}
this.setUpdateUI({ status: `v${result.latestVersion} available`, button: 'Download', state: 'available' });
}
async downloadUpdate() {
this.setUpdateUI({ status: '0%', button: 'Download', progress: true, disabled: true, state: 'downloading' });
const fill = document.getElementById('updateBarFill');
if (fill) fill.style.width = '0%';
const result = await ipcRenderer.invoke('updates-download');
if (!result.success) {
this.setUpdateUI({
status: `Download failed: ${result.error}`,
button: 'Retry',
state: 'error',
offerManual: true
});
return;
}
this.setUpdateUI({ status: 'Update ready', button: 'Install', state: 'ready' });
this.showUpdateBadge(true);
}
async installUpdate() {
this.setUpdateUI({ status: 'Installing…', button: 'Install', disabled: true, state: 'installing' });
const result = await ipcRenderer.invoke('updates-install');
if (!result.success) {
this.setUpdateUI({
status: result.error,
button: 'Retry',
state: 'error',
offerManual: true
});
this.updateState = 'ready';
return;
}
if (result.quitting) {
this.setUpdateUI({ status: 'Restarting…', button: 'Install', disabled: true, state: 'installing' });
} else if (result.manual) {
this.setUpdateUI({
status: 'Finish there, then restart Multi Browser',
button: 'Check',
state: 'idle'
});
} else {
this.setUpdateUI({ status: 'Installer opened', button: 'Check', state: 'idle' });
}
}
// ── Theme: 'system' (default) | 'light' | 'dark' ──
async loadTheme() {
let theme = 'system';
try {
theme = await ipcRenderer.invoke('get-ui-theme') || 'system';
} catch {
// Fall back to following the system.
}
this.applyTheme(theme);
}
applyTheme(theme) {
document.documentElement.dataset.theme = theme;
document.querySelectorAll('.theme-opt').forEach(btn => {
btn.setAttribute('aria-pressed', String(btn.dataset.themeChoice === theme));
});
}
setupThemeSwitch() {
const swtch = document.getElementById('themeSwitch');
if (!swtch) return;
swtch.addEventListener('click', async (e) => {
const btn = e.target.closest('.theme-opt');
if (!btn) return;
const theme = btn.dataset.themeChoice;
this.applyTheme(theme);
try {
await ipcRenderer.invoke('save-ui-theme', theme);
} catch (error) {
console.error('Could not save theme:', error);
}
});
}
async loadAppVersion() {
try {
const version = await ipcRenderer.invoke('get-app-version');
const label = document.getElementById('appVersionLabel');
if (label && version) label.textContent = `Multi Browser v${version}`;
} catch {
// Label keeps its static fallback text.
}
}
async loadSessions() {
const container = document.getElementById('welcomeSessionsContainer');
container.innerHTML = '<div class="loading">Loading sessions</div>';
try {
const sessions = await ipcRenderer.invoke('get-sessions');
this.renderSessions(sessions);
// Automatically open sessions marked for auto-open with a delay
const sessionsToOpen = sessions.filter(s => s.autoOpen);
if (sessionsToOpen.length > 0) {
for (let i = 0; i < sessionsToOpen.length; i++) {
const session = sessionsToOpen[i];
try {
// Add a delay between opening each session to prevent overwhelming resources
await new Promise(resolve => setTimeout(resolve, 500 * i));
await this.openSessionTab(session);
} catch (error) {
console.error(`Error opening session ${session.name}:`, error);
this.showNotification(`Failed to open session "${session.name}": ${error.message}`, 'error');
}
}
}
} catch (error) {
container.innerHTML = '<div class="error">Error loading sessions</div>';
}
}
renderSessions(sessions) {
const welcomeContainer = document.getElementById('welcomeSessionsContainer');
const countEl = document.getElementById('sessionCount');
if (countEl) {
countEl.textContent = sessions.length
? `${sessions.length} ${sessions.length === 1 ? 'session' : 'sessions'}`
: '';
}
if (sessions.length === 0) {
const emptyState = `
<div class="empty-state">
<h3>No sessions yet</h3>
<p>Create one to get an isolated browser with its own cookies and logins.</p>
</div>
`;
welcomeContainer.innerHTML = emptyState;
return;
}
// Store sessions for easy access
this.sessions.clear();
this.originalSessionNames.clear(); // Clear original names
sessions.forEach(session => {
this.sessions.set(session.id, session);
this.originalSessionNames.set(session.id, session.name); // Store original name
});
// Sort sessions by last accessed (most recent first)
sessions.sort((a, b) => new Date(b.lastAccessed) - new Date(a.lastAccessed));
// Generate welcome tab sessions (expanded view with more actions)
const welcomeHtml = sessions.map((session, i) => `
<article class="welcome-session-item" style="--i:${i}">
<div class="session-head">
<span class="session-avatar" data-session-avatar="${session.id}">${this.avatarContent(session)}</span>
<div class="session-info">
<h4>${this.escapeHtml(session.name)}</h4>
<div class="session-url" title="${this.escapeHtml(session.url)}">${this.escapeHtml(this.prettyUrl(session.url))}</div>
</div>
</div>
<dl class="session-meta">
<div><dt>Created</dt><dd>${this.formatDate(session.created)}</dd></div>
<div><dt>Last used</dt><dd>${this.formatDate(session.lastAccessed)}</dd></div>
</dl>
<div class="session-actions">
<label class="auto-open-toggle" title="Automatically open this session on startup">
<input type="checkbox"
${session.autoOpen ? 'checked' : ''}
onchange="ui.toggleAutoOpen('${session.id}', this.checked)">
<span class="track"></span>
Auto open
</label>
<span class="spacer"></span>
<button class="btn btn-primary btn-small" onclick="ui.openSessionTab('${session.id}')">
${ICONS.open} Open
</button>
<button class="icon-btn" title="Rename" onclick="ui.showRenameModal('${session.id}')">
${ICONS.pen}
</button>
<button class="icon-btn danger" title="Delete" onclick="ui.deleteSession('${session.id}')">
${ICONS.trash}
</button>
</div>
</article>
`).join('');
// Update both containers
welcomeContainer.innerHTML = welcomeHtml;
}
async toggleAutoOpen(sessionId, isChecked) {
try {
const result = await ipcRenderer.invoke('update-session-auto-open', sessionId, isChecked);
if (result.success) {
// Update local session data
const session = this.sessions.get(sessionId);
if (session) {
session.autoOpen = isChecked;
this.sessions.set(sessionId, session);
}
console.log(`Auto-open for session ${sessionId} set to ${isChecked}`);
} else {
this.showNotification(`Failed to update auto-open: ${result.error}`, 'error');
// Revert checkbox state
this.loadSessions();
}
} catch (error) {
console.error('Error toggling auto-open:', error);
this.showNotification(`Error: ${error.message}`, 'error');
}
}
async openSessionTab(sessionIdOrData) {
let sessionData;
if (typeof sessionIdOrData === 'string') {
// It's a session ID
sessionData = this.sessions.get(sessionIdOrData);
if (!sessionData) {
this.showNotification('Session not found', 'error');
return;
}
} else {
// It's session data object
sessionData = sessionIdOrData;
}
// Check if tab is already open
if (this.activeTabs.has(sessionData.id)) {
this.switchToTab(sessionData.id);
return;
}
try {
// Create tab
this.createTab(sessionData);
// Create browser view
await this.createBrowserViewTab(sessionData);
// Switch to the new tab
this.switchToTab(sessionData.id);
this.showNotification(`Opened session: ${sessionData.name} `, 'success');
} catch (error) {
this.showNotification(`Error opening session: ${error.message} `, 'error');
}
}
createTab(sessionData) {
const tabsContainer = document.getElementById('tabsContainer');
// Store original session name
this.originalSessionNames.set(sessionData.id, sessionData.name);
const tab = document.createElement('div');
tab.className = 'tab';
tab.dataset.tabId = sessionData.id;
tab.innerHTML = `
<span class="tab-title">${this.escapeHtml(sessionData.name)}</span>
<button class="tab-close" onclick="ui.closeTab('${sessionData.id}')" title="Close tab">${ICONS.close}</button>
`;
tab.addEventListener('click', (e) => {
// closest(): the close button holds an <svg>, so the click target
// is usually a path inside it, not the button itself.
if (!e.target.closest('.tab-close')) {
this.switchToTab(sessionData.id);
}
});
tabsContainer.appendChild(tab);
this.activeTabs.set(sessionData.id, tab);
}
async createBrowserViewTab(sessionData) {
const contentArea = document.querySelector('.content-area');
const tabContent = document.createElement('div');
tabContent.className = 'tab-content';
tabContent.id = `tab-${sessionData.id}`;
// Create a placeholder div for the browser view
const browserContainer = document.createElement('div');
browserContainer.className = 'browser-container';
browserContainer.innerHTML = `
<div class="view-placeholder">
<div class="ph-mark">${ICONS.globe}</div>
<div class="ph-name">${this.escapeHtml(sessionData.name)}</div>
<div class="ph-sub">${this.escapeHtml(sessionData.url)}</div>
</div>
`;
tabContent.appendChild(browserContainer);
contentArea.appendChild(tabContent);
console.log('Creating browser view for:', sessionData.name, 'URL:', sessionData.url);
// Create the browser view in the main process
const result = await ipcRenderer.invoke('create-browser-view', sessionData.id);
if (result.success) {
console.log(`✅ Browser view created for session: ${sessionData.name} `);
} else {
console.error(`❌ Failed to create browser view: `, result.error);
browserContainer.innerHTML = `
<div class="view-placeholder">
<div class="ph-mark" style="color: var(--danger); border-color: rgba(226,112,95,.3);">${ICONS.alert}</div>
<div class="ph-name">Failed to load ${this.escapeHtml(sessionData.name)}</div>
<div class="ph-sub">${this.escapeHtml(String(result.error))}</div>
<button class="btn btn-secondary btn-small" style="margin-top:12px"
onclick="ui.retryBrowserView('${sessionData.id}')">Retry</button>
</div>
`;
}
}
async updateSessionUrl(sessionId, url) {
try {
// Update the session data
const sessionData = this.sessions.get(sessionId);
if (sessionData) {
sessionData.url = url;
sessionData.lastAccessed = new Date().toISOString();
// Update in database (we'll need to add this IPC handler)
// For now, we'll just update locally
this.sessions.set(sessionId, sessionData);
}
} catch (error) {
console.error('Error updating session URL:', error);
}
}
async switchToTab(tabId) {
// Remove active class from all tabs and content
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Remove active class from session items
document.querySelectorAll('.session-item').forEach(item => item.classList.remove('active'));
// Hide current browser view
if (this.activeTabId && this.activeTabId !== 'welcome' && this.activeTabId !== tabId) {
await ipcRenderer.invoke('hide-browser-view', this.activeTabId);
}
// Add active class to selected tab and content
const selectedTab = document.querySelector(`[data-tab-id="${tabId}"]`);
const selectedContent = document.getElementById(`tab-${tabId}`);
if (selectedTab) {
selectedTab.classList.add('active');
}
if (selectedContent) {
selectedContent.classList.add('active');
}
// Show browser view for this tab (if it's not welcome)
if (tabId !== 'welcome') {
await ipcRenderer.invoke('show-browser-view', tabId);
} else {
// When switching to welcome, make sure no browser view is shown
console.log('Switching to welcome tab - hiding all browser views');
// Hide any active browser view when switching to welcome
if (this.activeTabId && this.activeTabId !== 'welcome') {
try {
await ipcRenderer.invoke('hide-browser-view', this.activeTabId);
} catch (error) {
console.log('Error hiding browser view:', error);
}
}
}
this.activeTabId = tabId;
}
async closeTab(sessionId) {
// Don't allow closing the welcome tab
if (sessionId === 'welcome') {
return;
}
const tab = this.activeTabs.get(sessionId);
const tabContent = document.getElementById(`tab-${sessionId}`);
// Close browser view
await ipcRenderer.invoke('close-browser-view', sessionId);
if (tab) {
tab.remove();
this.activeTabs.delete(sessionId);
}
if (tabContent) {
tabContent.remove();
}
// If this was the active tab, switch to welcome or another tab
if (this.activeTabId === sessionId) {
if (this.activeTabs.size > 0) {
// Switch to the first available tab
const firstTabId = this.activeTabs.keys().next().value;
await this.switchToTab(firstTabId);
} else {
// Switch to welcome tab
await this.switchToTab('welcome');
}
}
// Remove active state from session item
const sessionItem = document.querySelector(`[data-session-id="${sessionId}"]`);
if (sessionItem) {
sessionItem.classList.remove('active');
}
}
async deleteSession(sessionId) {
if (!confirm('Are you sure you want to delete this session? This will remove all associated data and cannot be undone.')) {
return;
}
try {
const result = await ipcRenderer.invoke('delete-session', sessionId);
if (result.success) {
this.showNotification('Session deleted successfully', 'success');
// Close the tab if it's open
if (this.activeTabs.has(sessionId)) {
await this.closeTab(sessionId);
}
// Remove from sessions map
this.sessions.delete(sessionId);
// Refresh the sessions list
this.loadSessions();
} else {
this.showNotification(`Error deleting session: ${result.error} `, 'error');
}
} catch (error) {
this.showNotification(`Error: ${error.message}`, 'error');
}
}
showNotification(message, type = 'info') {
const statusBar = document.getElementById('status-bar');
const statusMessage = document.getElementById('status-message');
if (statusBar && statusMessage) {
// Show the message
statusMessage.textContent = message;
statusBar.className = `status-bar show ${type}`;
ipcRenderer.send('status-bar-visibility', true);
// After 3 seconds, show "Ready" for 2 seconds, then hide
setTimeout(() => {
statusBar.className = 'status-bar show';
statusMessage.textContent = 'Ready';
// Hide after 2 more seconds
setTimeout(() => {
statusBar.className = 'status-bar';
ipcRenderer.send('status-bar-visibility', false);
}, 2000);
}, 3000);
}
}
formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// Session cards show the site's favicon once we've seen one (stored by the
// main process on page-favicon-updated); until then, the name's initial.
avatarContent(session) {
const initial = this.escapeHtml((session.name || '?').trim().charAt(0));
if (!session.favicon) return initial;
return `<img src="${this.escapeHtml(session.favicon)}" alt=""
onerror="this.replaceWith(document.createTextNode('${initial.replace(/'/g, "\\'")}'))">`;
}
// Cards show the host, not the whole URL — the full value stays in the title.
prettyUrl(url) {
try {
const u = new URL(url);
return (u.hostname + (u.pathname === '/' ? '' : u.pathname)).replace(/^www\./, '');
} catch {
return url || 'about:blank';
}
}
async retryBrowserView(sessionId) {
const sessionData = this.sessions.get(sessionId);
if (sessionData) {
console.log(`🔄 Retrying browser view for ${sessionData.name}`);
// Close existing browser view
await ipcRenderer.invoke('close-browser-view', sessionId);
// Create new browser view
const result = await ipcRenderer.invoke('create-browser-view', sessionId);
if (result.success) {
console.log(`✅ Browser view recreated for ${sessionData.name}`);
// Show the browser view if this tab is active
if (this.activeTabId === sessionId) {
await ipcRenderer.invoke('show-browser-view', sessionId);
}
}
}
}
updateTabTitleWithUnreadCount(sessionId, title, unreadCount) {
const tab = this.activeTabs.get(sessionId);
if (tab) {
const titleSpan = tab.querySelector('.tab-title');
if (titleSpan) {
// Get original session name
const sessionData = this.sessions.get(sessionId);
const originalName = this.originalSessionNames.get(sessionId) || sessionData?.name || 'Session';
// Build display title with unread count
let displayTitle = originalName;
if (unreadCount && unreadCount !== 0 && unreadCount !== '0') {
displayTitle = `(${unreadCount}) ${originalName} `;
}
// Preserve favicon if it exists
const existingFavicon = titleSpan.querySelector('.tab-favicon');
const truncatedTitle = displayTitle.length > 20 ? displayTitle.substring(0, 20) + '...' : displayTitle;
if (existingFavicon) {
titleSpan.innerHTML = '';
titleSpan.appendChild(existingFavicon);
titleSpan.appendChild(document.createTextNode(truncatedTitle));
} else {
titleSpan.textContent = truncatedTitle;
}
console.log(`📄 Updated tab title for ${sessionId}: ${displayTitle} (from original: ${originalName})`);
}
}