-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.js
More file actions
1104 lines (964 loc) · 48.4 KB
/
browser.js
File metadata and controls
1104 lines (964 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// browser.js
// Consumes <browserbox-webview> API directly — no wrapper layer.
// This is a tier-1 reference for embedding BrowserBox with custom chrome.
import './browserbox-webview.js';
// Debug: track how many instances are created
let browserAppInstanceCounter = 0;
export class BrowserApp {
// Internal view-model for tabs (sync state for UI rendering)
#tabs = new Map();
#tabOrder = [];
#activeTabId = null;
#instanceId;
#apiSynced = false; // Flag: ignore tab-created events until initial sync complete
#pendingCreateTab = false; // Tracks whether a local createTab call is in-flight
#createTabTimestamp = 0; // When we last called createTab (for time-window deduplication)
#refreshMetadataTimer = null; // Debounce timer for metadata refresh
#activeTabSyncTimer = null; // Debounce timer for syncing active tab from API
#throbberStuckTimer = null; // Safety: auto-stop throbber after max duration
constructor(windowEl, windowInstanceId, webviewId, isNetscape, appDef) {
this.#instanceId = ++browserAppInstanceCounter;
this.#apiSynced = false;
console.log(`[BrowserApp] Creating instance #${this.#instanceId} for webviewId=${webviewId}`);
this.netscape = !!isNetscape;
this.appDef = appDef;
this.windowEl = windowEl;
this.windowInstanceId = windowInstanceId;
this.webviewId = webviewId;
// Query for <browserbox-webview> element directly
this.webviewEl = this.windowEl.querySelector(`#${this.webviewId}`);
this.defaultUrl = "about:blank";
this.homeUrl = "https://browserbox.io";
if (this.netscape) {
this.throbberAnimatedSrc = "./netscape.gif";
this.throbberStaticSrc = "./netscape-frame.gif";
} else {
this.throbberAnimatedSrc = "./Internet_Explorer_gif.webp";
this.throbberStaticSrc = "./ie_static.png";
}
this.defaultFavicon = "./template_world-4.png";
this.ui = {
menuBar: {
file: this.windowEl.querySelector('[data-menu-item="file"]'),
edit: this.windowEl.querySelector('[data-menu-item="edit"]'),
view: this.windowEl.querySelector('[data-menu-item="view"]'),
favorites: this.windowEl.querySelector('[data-menu-item="favorites"]'),
tools: this.windowEl.querySelector('[data-menu-item="tools"]'),
help: this.windowEl.querySelector('[data-menu-item="help"]'),
},
navButtons: {
back: this.windowEl.querySelector('.browser-nav-button-back'),
forward: this.windowEl.querySelector('.browser-nav-button-forward'),
stop: this.windowEl.querySelector('.browser-nav-button-stop'),
refresh: this.windowEl.querySelector('.browser-nav-button-refresh'),
home: this.windowEl.querySelector('.browser-nav-button-home'),
search: this.windowEl.querySelector('.browser-nav-button-search'),
favorites: this.windowEl.querySelector('.browser-nav-button-favorites'),
history: this.windowEl.querySelector('.browser-nav-button-history')
},
addressBar: this.windowEl.querySelector('.browser-address-bar-input'),
goButton: this.windowEl.querySelector('.browser-address-bar-go'),
linksButton: this.windowEl.querySelector('.browser-address-bar-links'),
throbber: this.windowEl.querySelector('.browser-throbber-netscape'),
tabBar: this.windowEl.querySelector('.browser-tab-bar-ie'),
newTabButton: this.windowEl.querySelector('.browser-new-tab-btn-ie'),
statusBar: {
statusIcon: this.windowEl.querySelector('.status-bar-icon-main img'),
statusText: this.windowEl.querySelector('.status-bar-text-main'),
zoneIcon: this.windowEl.querySelector('.status-bar-icon-zone img'),
zoneText: this.windowEl.querySelector('.status-bar-zone-text')
}
};
this._setupEventListeners();
if (this.ui.navButtons.stop) this.ui.navButtons.stop.style.display = 'none';
if (this.ui.navButtons.refresh) this.ui.navButtons.refresh.style.display = 'flex';
if (this.ui.throbber) {
this.ui.throbber.src = this.throbberStaticSrc;
this.ui.throbber.style.display = 'block';
this.ui.throbber.classList.remove('throbber-active');
}
this._updateNavButtonStates();
this.setStatusBarText("Done", "./channels-4.png");
if (this.ui.statusBar.zoneIcon) this.ui.statusBar.zoneIcon.src = './internet_connection_wiz-0.png';
if (this.ui.statusBar.zoneText) this.ui.statusBar.zoneText.textContent = "BrowserBox";
}
static generateInitialHTML(webviewId, launchData = {}) {
const menuItems = [
{ label: "<u>F</u>ile", action: "file" },
{ label: "<u>E</u>dit", action: "edit" },
{ label: "<u>V</u>iew", action: "view" },
{ label: "F<u>a</u>vorites", action: "favorites" },
{ label: "<u>T</u>ools", action: "tools" },
{ label: "<u>H</u>elp", action: "help" }
];
const mainButtonLabels = {
back: "Back", forward: "Forward", stop: "Stop", refresh: "Refresh",
home: "Home", search: "Search", favorites: "Favorites", history: "History"
};
const rawLoginLink = typeof launchData?.loginLink === 'string' ? launchData.loginLink : '';
const sanitizedLoginLink = rawLoginLink
.replaceAll('&', '&')
.replaceAll('"', '"')
.replaceAll('<', '<')
.replaceAll('>', '>');
const loginLinkAttr = sanitizedLoginLink ? ` login-link="${sanitizedLoginLink}"` : '';
return `
<div class="browser-container-ie">
<div class="browser-toolbars-wrapper-ie">
<div class="browser-menu-bar-ie">
${menuItems.map(item => `<button data-menu-item="${item.action}" disabled>${item.label}</button>`).join('')}
</div>
<div class="browser-main-toolbar-ie">
<div class="browser-nav-buttons-ie">
<button class="browser-nav-button-back" data-action="back" title="Back"><span class="icon-area"></span><span>${mainButtonLabels.back}</span></button>
<button class="browser-nav-button-forward" data-action="forward" title="Forward"><span class="icon-area"></span><span>${mainButtonLabels.forward}</span></button>
<span class="toolbar-separator"></span>
<button class="browser-nav-button-stop" data-action="stop" title="Stop"><span class="icon-area"></span><span>${mainButtonLabels.stop}</span></button>
<button class="browser-nav-button-refresh" data-action="refresh" title="Refresh"><span class="icon-area"></span><span>${mainButtonLabels.refresh}</span></button>
<span class="toolbar-separator"></span>
<button class="browser-nav-button-home" data-action="home" title="Home"><span class="icon-area"></span><span>${mainButtonLabels.home}</span></button>
<span class="toolbar-separator"></span>
<button class="browser-nav-button-search" data-action="search" title="Search"><span class="icon-area"></span><span>${mainButtonLabels.search}</span></button>
<button class="browser-nav-button-favorites" data-action="favorites" title="Favorites"><span class="icon-area"></span><span>${mainButtonLabels.favorites}</span></button>
<button class="browser-nav-button-history" data-action="history" title="History"><span class="icon-area"></span><span>${mainButtonLabels.history}</span></button>
</div>
<img src="" alt="Activity" class="browser-throbber-netscape">
</div>
<div class="browser-address-toolbar-ie">
<label for="address-${webviewId}" class="browser-address-bar-label">Address</label>
<input type="text" id="address-${webviewId}" class="browser-address-bar-input" value="">
<button class="browser-address-bar-go" data-action="go" title="Go to address">
<span class="icon-area icon-go"></span>Go
</button>
<button class="browser-address-bar-links" data-action="links" disabled>Links »</button>
</div>
<div class="browser-tab-bar-ie">
<button class="browser-new-tab-btn-ie" title="New Tab">+</button>
</div>
</div>
<div class="browser-content">
<browserbox-webview id="${webviewId}"${loginLinkAttr}
style="display:block; width:100%; height:100%;"
request-timeout-ms="45000">
</browserbox-webview>
</div>
<div class="browser-status-bar-ie">
<div class="status-bar-panel status-bar-main">
<img src="./channels-4.png" alt="" class="status-bar-icon-main"/>
<span class="status-bar-text-main">Done</span>
</div>
<div class="status-bar-panel status-bar-short"></div>
<div class="status-bar-panel status-bar-short"></div>
<div class="status-bar-panel status-bar-zone">
<img src="./internet_connection_wiz-0.png" alt="Zone" class="status-bar-icon-zone"/>
<span class="status-bar-zone-text"></span>
</div>
</div>
</div>
`;
}
_setupEventListeners() {
// Nav button handlers — call BBX API directly
this.ui.navButtons.back.addEventListener('click', () => this.goBack());
this.ui.navButtons.forward.addEventListener('click', () => this.goForward());
this.ui.navButtons.stop.addEventListener('click', () => this.stopLoading());
this.ui.navButtons.refresh.addEventListener('click', () => this.reloadPage());
this.ui.navButtons.home.addEventListener('click', () => this.navigateTo(this.homeUrl));
this.ui.navButtons.search.addEventListener('click', () => this.navigateTo('https://google.com'));
this.ui.navButtons.favorites.addEventListener('click', () => this.navigateTo('chrome://bookmarks'));
this.ui.navButtons.history.addEventListener('click', () => this.navigateTo('chrome://history'));
if (this.ui.linksButton) {
this.ui.linksButton.addEventListener('click', () => alert('Links action not implemented.'));
}
// Address bar — navigate via BBX submitOmnibox API
this.ui.addressBar.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.navigateToCurrentAddress();
});
this.ui.goButton.addEventListener('click', () => this.navigateToCurrentAddress());
// Tab bar click delegation
if (this.ui.tabBar) {
this.ui.tabBar.addEventListener('click', async (e) => {
const tabElement = e.target.closest('.browser-tab-ie');
if (!tabElement) {
console.log('[BrowserApp] Tab bar click: no tab element found, target:', e.target.className);
return;
}
const tabIndex = parseInt(tabElement.dataset.tabIndex, 10);
console.log('[BrowserApp] Tab bar click: tabIndex=', tabIndex, 'target=', e.target.className);
if (e.target.classList.contains('tab-close-btn-ie')) {
// Close tab via BBX API
try {
await this.webviewEl.closeTab(tabIndex);
} catch (err) {
console.error('[BrowserApp] closeTab failed:', err);
}
} else {
// Switch tab via BBX API
try {
await this.webviewEl.switchToTab(tabIndex);
} catch (err) {
console.error('[BrowserApp] switchToTab failed:', err);
}
}
});
}
// New tab button — create tab via BBX API
if (this.ui.newTabButton) {
this.ui.newTabButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
console.log('[BrowserApp] New tab button clicked, _creatingTab=', this._creatingTab);
// Debounce rapid clicks
if (this._creatingTab) {
console.log('[BrowserApp] New tab button: debounce guard active, ignoring click');
return;
}
this._creatingTab = true;
// Set pending flag so we only accept ONE tab-created event
this.#pendingCreateTab = true;
this.#createTabTimestamp = Date.now();
console.log('[BrowserApp] New tab button: calling createTab...');
this.webviewEl.createTab(this.defaultUrl)
.then(() => {
console.log('[BrowserApp] New tab button: createTab succeeded');
})
.catch((err) => {
console.error('[BrowserApp] New tab button: createTab failed:', err);
// Clear pending on error
this.#pendingCreateTab = false;
})
.finally(() => {
setTimeout(() => {
this._creatingTab = false;
console.log('[BrowserApp] New tab button: debounce guard cleared');
}, 300);
});
});
}
// BBX API events — directly from <browserbox-webview>
this.webviewEl.addEventListener('ready', () => this._handleReady());
this.webviewEl.addEventListener('api-ready', (e) => this._handleApiReady(e.detail));
this.webviewEl.addEventListener('tab-created', (e) => this._handleTabCreated(e.detail));
this.webviewEl.addEventListener('tab-closed', (e) => this._handleTabClosed(e.detail));
this.webviewEl.addEventListener('tab-updated', (e) => this._handleTabUpdated(e.detail));
this.webviewEl.addEventListener('active-tab-changed', (e) => this._handleActiveTabChanged(e.detail));
this.webviewEl.addEventListener('did-start-loading', (e) => this._handleDidStartLoading(e.detail));
this.webviewEl.addEventListener('did-stop-loading', (e) => this._handleDidStopLoading(e.detail));
this.webviewEl.addEventListener('did-navigate', (e) => this._handleDidNavigate(e.detail));
this.webviewEl.addEventListener('favicon-changed', (e) => this._handleFaviconChanged(e.detail));
this.webviewEl.addEventListener('policy-denied', (e) => {
console.warn('[BrowserApp] Policy denied:', e.detail);
});
}
setStatusBarText(text, iconSrc = null) {
if (this.ui.statusBar.statusText) {
this.ui.statusBar.statusText.textContent = text;
}
if (iconSrc && this.ui.statusBar.statusIcon) {
this.ui.statusBar.statusIcon.src = iconSrc;
this.ui.statusBar.statusIcon.style.display = 'inline';
} else if (this.ui.statusBar.statusIcon) {
this.ui.statusBar.statusIcon.style.display = 'none';
}
}
// --- Internal view model helpers ---
#getActiveTab() {
return this.#activeTabId ? this.#tabs.get(this.#activeTabId) : null;
}
#upsertTab(detail, allowInsert = false) {
const tabId = this.#extractTabId(detail);
if (!tabId) return null;
// Only insert new tabs if explicitly allowed (from _handleTabCreated)
// Otherwise only update existing tabs
if (!this.#tabs.has(tabId) && !allowInsert) {
return null;
}
const existing = this.#tabs.get(tabId) || {
id: tabId,
url: '',
title: 'New Tab',
loading: false,
canGoBack: null,
canGoForward: null,
faviconDataURI: '',
isDefaultFavicon: true,
};
const url = typeof detail.url === 'string' ? detail.url : existing.url;
// Preserve existing title unless the event provides a real (non-empty) one.
// An empty-string title must NOT overwrite a previously-known good title.
const title = (typeof detail.title === 'string' && detail.title.length > 0)
? detail.title
: (existing.title && existing.title !== 'New Tab' ? existing.title : this.#extractTitleFromUrl(url));
let isDefaultFavicon = this.#resolveDefaultFaviconFlag(detail, existing.isDefaultFavicon ?? true);
const hasExistingNonDefaultFavicon = Boolean(existing.faviconDataURI) && existing.isDefaultFavicon === false;
const detailHasExplicitFavicon = (
typeof detail.faviconDataURI === 'string' && detail.faviconDataURI.length > 0
);
const existingOrigin = this.#originFromUrl(existing.url);
const nextOrigin = this.#originFromUrl(url);
const sameOriginNavigation = Boolean(existingOrigin && nextOrigin && existingOrigin === nextOrigin);
// Prevent race regressions where metadata briefly reports "default favicon"
// after we already have a real favicon for the same origin.
if (isDefaultFavicon && hasExistingNonDefaultFavicon && sameOriginNavigation && !detailHasExplicitFavicon) {
isDefaultFavicon = false;
}
const next = {
...existing,
id: tabId,
url,
title,
loading: typeof detail.loading === 'boolean' ? detail.loading : existing.loading,
canGoBack: typeof detail.canGoBack === 'boolean' ? detail.canGoBack : existing.canGoBack,
canGoForward: typeof detail.canGoForward === 'boolean' ? detail.canGoForward : existing.canGoForward,
faviconDataURI: (typeof detail.faviconDataURI === 'string' && detail.faviconDataURI.length > 0)
? detail.faviconDataURI
: existing.faviconDataURI,
isDefaultFavicon,
};
if (!this.#tabOrder.includes(tabId)) {
this.#tabOrder.push(tabId);
}
this.#tabs.set(tabId, next);
return next;
}
#extractTabId(detail) {
if (!detail || typeof detail !== 'object') return null;
const candidates = [detail.id, detail.tabId, detail.targetId];
for (const c of candidates) {
if (typeof c === 'string' && c.length > 0) return c;
}
if (Number.isInteger(detail.index) && detail.index >= 0) {
return this.#tabOrder[detail.index] || null;
}
return null;
}
#extractApiTabId(tab) {
if (tab && typeof tab === 'object') {
const id = tab.id || tab.targetId || tab.tabId;
if (typeof id === 'string' && id.length > 0) return id;
}
return null;
}
#reconcileTabOrderFromApi(apiTabs) {
if (!Array.isArray(apiTabs) || apiTabs.length === 0) return false;
const nextOrder = [];
for (const apiTab of apiTabs) {
const tabId = this.#extractApiTabId(apiTab);
if (!tabId || nextOrder.includes(tabId)) continue;
nextOrder.push(tabId);
}
for (const tabId of this.#tabOrder) {
if (this.#tabs.has(tabId) && !nextOrder.includes(tabId)) {
nextOrder.push(tabId);
}
}
if (nextOrder.length === 0) return false;
const previous = this.#tabOrder.join(',');
const next = nextOrder.join(',');
if (previous === next) return false;
this.#tabOrder = nextOrder;
console.log(`[BrowserApp ${this.webviewId}] Reconciled tab order with API`, {
previousOrder: previous,
nextOrder: next,
});
return true;
}
#extractFaviconUri(faviconData) {
if (!faviconData) return '';
if (typeof faviconData === 'string') return faviconData;
if (typeof faviconData !== 'object') return '';
return (
faviconData.dataURI ||
faviconData.src ||
faviconData.faviconDataURI ||
faviconData.faviconDataUrl ||
''
);
}
#resolveDefaultFaviconFlag(detail, fallback = true) {
if (!detail || typeof detail !== 'object') return fallback;
if (typeof detail.isDefaultFavicon === 'boolean') return detail.isDefaultFavicon;
if (typeof detail.defaultFavicon === 'boolean') return detail.defaultFavicon;
if (typeof detail.usingDefaultFavicon === 'boolean') return detail.usingDefaultFavicon;
const favicon = detail.faviconDataURI || detail.favicon;
if (typeof favicon === 'string' && favicon.length > 0) return false;
return fallback;
}
#setAddressBarUrl(url) {
this.ui.addressBar.value = (url && url !== 'about:blank') ? url : '';
}
#extractTitleFromUrl(url) {
if (!url || typeof url !== 'string') return 'Untitled';
if (url === 'about:blank') return 'Blank Page';
try {
return new URL(url).hostname || 'Untitled';
} catch {
return url.substring(0, 20);
}
}
#originFromUrl(url) {
if (!url || typeof url !== 'string' || url === 'about:blank') {
return '';
}
try {
return new URL(url).origin;
} catch {
return '';
}
}
// --- BBX API event handlers ---
async _handleReady() {
console.log(`[BrowserApp ${this.webviewId}] BBX ready event`);
// Also sync on ready in case api-ready doesn't fire
if (!this.#apiSynced) {
await this._doInitialSync();
}
}
async _handleApiReady(detail) {
console.log(`[BrowserApp ${this.webviewId}] BBX api-ready:`, detail);
// Sync tabs from BBX API
if (!this.#apiSynced) {
await this._doInitialSync();
}
}
#syncInProgress = false;
async _doInitialSync() {
// Prevent concurrent syncs
if (this.#syncInProgress || this.#apiSynced) {
console.log(`[BrowserApp ${this.webviewId}] Sync already in progress or complete, skipping`);
return;
}
this.#syncInProgress = true;
try {
await this.#syncTabsFromApi();
// Ensure at least one tab exists
if (this.#tabs.size === 0) {
console.log(`[BrowserApp ${this.webviewId}] No tabs after sync, creating default tab`);
this.#pendingCreateTab = true;
this.#createTabTimestamp = Date.now();
await this.webviewEl.createTab(this.defaultUrl);
}
// Mark sync complete - now tab-created events can be processed
this.#apiSynced = true;
console.log(`[BrowserApp ${this.webviewId}] Initial sync complete, ${this.#tabs.size} tabs`);
this._renderTabs();
this._updateNavButtonStates();
const activeTab = this.#getActiveTab();
if (activeTab) {
this.#setAddressBarUrl(activeTab.url);
this._updateWindowTitle(activeTab.title);
}
this.setStatusBarText("Done", "./channels-4.png");
} finally {
this.#syncInProgress = false;
}
}
async #syncTabsFromApi() {
try {
const apiTabs = await this.webviewEl.getTabs();
const activeIndex = await this.webviewEl.getActiveTabIndex();
this.#tabs.clear();
this.#tabOrder = [];
for (const tab of (Array.isArray(apiTabs) ? apiTabs : [])) {
const tabId = this.#extractApiTabId(tab);
if (!tabId) continue;
this.#tabOrder.push(tabId);
this.#tabs.set(tabId, {
id: tabId,
url: tab.url || '',
title: tab.title || this.#extractTitleFromUrl(tab.url),
loading: false,
canGoBack: typeof tab.canGoBack === 'boolean' ? tab.canGoBack : null,
canGoForward: typeof tab.canGoForward === 'boolean' ? tab.canGoForward : null,
faviconDataURI: tab.faviconDataURI || '',
isDefaultFavicon: tab.isDefaultFavicon ?? true,
});
}
const apiActiveTab = Array.isArray(apiTabs)
? apiTabs.find((tab) => tab?.active === true)
: null;
const apiActiveTabId = this.#extractApiTabId(apiActiveTab);
if (apiActiveTabId && this.#tabs.has(apiActiveTabId)) {
this.#activeTabId = apiActiveTabId;
} else if (Number.isInteger(activeIndex) && activeIndex >= 0 && activeIndex < this.#tabOrder.length) {
this.#activeTabId = this.#tabOrder[activeIndex];
} else {
this.#activeTabId = this.#tabOrder[0] || null;
}
} catch (err) {
console.warn('[BrowserApp] Failed to sync tabs:', err);
}
}
_handleTabCreated(detail) {
const tabId = this.#extractTabId(detail);
const now = Date.now();
const timeSinceCreate = now - this.#createTabTimestamp;
const wasPendingCreate = this.#pendingCreateTab;
console.log(`[BrowserApp ${this.webviewId}] Tab created event:`, tabId,
'apiSynced:', this.#apiSynced,
'hasTab:', this.#tabs.has(tabId),
'pendingCreateTab:', this.#pendingCreateTab,
'timeSinceCreate:', timeSinceCreate);
// Ignore tab-created events until initial sync is complete
if (!this.#apiSynced) {
console.log(`[BrowserApp ${this.webviewId}] Ignoring tab-created before initial sync`);
return;
}
// Skip if we already have this tab (avoid duplicate events for same tabId)
if (tabId && this.#tabs.has(tabId)) {
console.log(`[BrowserApp ${this.webviewId}] Tab ${tabId} already exists, skipping`);
return;
}
console.log(`[BrowserApp ${this.webviewId}] Adding new tab ${tabId}, current count:`, this.#tabs.size);
this.#upsertTab(detail, true); // allowInsert = true for new tabs
// Clear pending only when this tab likely came from our own createTab flow.
// Externally-created tabs (e.g. context menu "open in new tab") are valid too.
if (wasPendingCreate) {
console.log(`[BrowserApp ${this.webviewId}] Cleared pendingCreateTab after accepting tab ${tabId}`);
this.#pendingCreateTab = false;
} else {
console.log(`[BrowserApp ${this.webviewId}] Accepted externally-created tab ${tabId}`);
}
console.log(`[BrowserApp ${this.webviewId}] After upsert, count:`, this.#tabs.size);
this._renderTabs();
this._scheduleActiveTabSync(120);
this._scheduleMetadataRefresh(200);
}
_handleTabClosed(detail) {
const tabId = this.#extractTabId(detail);
console.log(`[BrowserApp ${this.webviewId}] Tab closed:`, tabId);
if (tabId) {
this.#tabs.delete(tabId);
this.#tabOrder = this.#tabOrder.filter(id => id !== tabId);
if (this.#activeTabId === tabId) {
this.#activeTabId = this.#tabOrder[0] || null;
}
}
this._renderTabs();
// If no tabs remain, create a new blank tab
if (this.#tabOrder.length === 0) {
this.webviewEl.createTab(this.defaultUrl);
}
}
_handleTabUpdated(detail) {
// console.log(`[BrowserApp ${this.webviewId}] Tab updated:`, detail);
const tab = this.#upsertTab(detail);
if (tab && tab.id === this.#activeTabId) {
this.#setAddressBarUrl(tab.url);
this._updateWindowTitle(tab.title);
this._updateNavButtonStates();
}
this._renderTabs();
}
_handleActiveTabChanged(detail) {
console.log(`[BrowserApp ${this.webviewId}] Active tab changed:`, detail);
const tabId = this.#extractTabId(detail);
const shouldInsert = Boolean(tabId && !this.#tabs.has(tabId));
const tab = this.#upsertTab(detail, shouldInsert);
this.#activeTabId = tab?.id || tabId;
if (shouldInsert) {
console.log(`[BrowserApp ${this.webviewId}] Inserted missing active tab ${tabId} from active-tab-changed`);
}
this.#setAddressBarUrl(detail.url || tab?.url);
this._updateWindowTitle(detail.title || tab?.title);
this._renderTabs();
this._updateNavButtonStates();
this.setStatusBarText("Done", "./channels-4.png");
if (shouldInsert) this._scheduleMetadataRefresh(200);
}
_handleDidStartLoading(detail) {
const tabId = this.#extractTabId(detail);
console.log(`[BrowserApp ${this.webviewId}] Loading started:`, tabId, 'activeTabId:', this.#activeTabId);
const tab = this.#tabs.get(tabId);
if (tab) {
tab.loading = true;
if (detail.url) tab.url = detail.url;
}
// Always update throbber for active tab OR if tabId is null (global loading indicator)
if (tabId === this.#activeTabId || !tabId) {
if (this.ui.navButtons.stop) this.ui.navButtons.stop.style.display = 'flex';
if (this.ui.navButtons.refresh) this.ui.navButtons.refresh.style.display = 'none';
this._startThrobber();
this.setStatusBarText(`Loading ${detail.url || '...'}`, "./channels-4.png");
}
this._renderTabs();
this._updateNavButtonStates();
}
_handleDidStopLoading(detail) {
const tabId = this.#extractTabId(detail);
console.log(`[BrowserApp ${this.webviewId}] Loading stopped:`, tabId, 'activeTabId:', this.#activeTabId);
const tab = this.#tabs.get(tabId);
if (tab) tab.loading = false;
// Always update throbber for active tab OR if tabId is null (global loading indicator)
if (tabId === this.#activeTabId || !tabId) {
if (this.ui.navButtons.stop) this.ui.navButtons.stop.style.display = 'none';
if (this.ui.navButtons.refresh) this.ui.navButtons.refresh.style.display = 'flex';
this._stopThrobber();
this.setStatusBarText("Done", "./channels-4.png");
}
this._renderTabs();
this._updateNavButtonStates();
// Refresh metadata after loading stops (title may update after initial load)
this._scheduleMetadataRefresh(1000);
}
_handleDidNavigate(detail) {
console.log(`[BrowserApp ${this.webviewId}] Navigation completed:`, detail);
const tab = this.#upsertTab({ ...detail, loading: false });
// Also stop throbber on navigation complete as a fallback
if (tab && tab.id === this.#activeTabId) {
if (this.ui.navButtons.stop) this.ui.navButtons.stop.style.display = 'none';
if (this.ui.navButtons.refresh) this.ui.navButtons.refresh.style.display = 'flex';
this._stopThrobber();
}
if (tab && tab.id === this.#activeTabId) {
this.#setAddressBarUrl(tab.url);
this._updateWindowTitle(tab.title);
this._updateNavButtonStates();
}
this._renderTabs();
this.setStatusBarText("Done", "./channels-4.png");
// Schedule metadata refresh to get final title/favicon after page fully loads
this._scheduleMetadataRefresh();
}
_handleFaviconChanged(detail) {
console.log(`[BrowserApp ${this.webviewId}] Favicon changed:`, detail);
const tabId = detail?.tabId;
if (!tabId) return;
const tab = this.#tabs.get(tabId);
if (!tab) return;
if (typeof detail.faviconDataURI === 'string' && detail.faviconDataURI.length > 0) {
tab.faviconDataURI = detail.faviconDataURI;
}
if (typeof detail.isDefaultFavicon === 'boolean') {
tab.isDefaultFavicon = detail.isDefaultFavicon;
}
this._renderTabs();
}
_scheduleMetadataRefresh(delayMs = 500) {
// Debounce: cancel any pending refresh and schedule a new one
if (this.#refreshMetadataTimer) {
clearTimeout(this.#refreshMetadataTimer);
}
this.#refreshMetadataTimer = setTimeout(() => this._refreshTabMetadata(), delayMs);
}
_scheduleActiveTabSync(delayMs = 100) {
if (this.#activeTabSyncTimer) {
clearTimeout(this.#activeTabSyncTimer);
}
this.#activeTabSyncTimer = setTimeout(() => this._syncActiveTabFromApi(), delayMs);
}
async _syncActiveTabFromApi() {
try {
const [apiTabs, activeIndex] = await Promise.all([
this.webviewEl.getTabs(),
this.webviewEl.getActiveTabIndex(),
]);
const orderChanged = this.#reconcileTabOrderFromApi(apiTabs);
const activeFromFlag = Array.isArray(apiTabs)
? apiTabs.find((tab) => tab?.active === true)
: null;
const activeFromIndex = (
Array.isArray(apiTabs) &&
Number.isInteger(activeIndex) &&
activeIndex >= 0 &&
activeIndex < apiTabs.length
) ? apiTabs[activeIndex] : null;
const activeTabId = this.#extractApiTabId(activeFromFlag) || this.#extractApiTabId(activeFromIndex);
if (!activeTabId) {
return;
}
const activeSource = activeFromFlag || activeFromIndex;
if (activeSource && !this.#tabs.has(activeTabId)) {
this.#upsertTab(activeSource, true);
}
if (!orderChanged && activeTabId === this.#activeTabId) {
return;
}
this.#activeTabId = activeTabId;
const activeTab = this.#tabs.get(activeTabId);
this.#setAddressBarUrl(activeTab?.url);
this._updateWindowTitle(activeTab?.title);
this._renderTabs();
this._updateNavButtonStates();
} catch (err) {
console.warn('[BrowserApp] Failed to sync active tab:', err);
}
}
// Force-restart animated image by clearing src first (browser skips reload if src unchanged)
_startThrobber() {
if (!this.ui.throbber) return;
clearTimeout(this.#throbberStuckTimer);
this.ui.throbber.src = '';
this.ui.throbber.src = this.throbberAnimatedSrc;
this.ui.throbber.classList.add('throbber-active');
// Safety: auto-stop after 60s to prevent stuck throbber
this.#throbberStuckTimer = setTimeout(() => this._stopThrobber(), 60000);
}
_stopThrobber() {
if (!this.ui.throbber) return;
clearTimeout(this.#throbberStuckTimer);
this.#throbberStuckTimer = null;
this.ui.throbber.src = this.throbberStaticSrc;
this.ui.throbber.classList.remove('throbber-active');
}
async _refreshTabMetadata() {
try {
const apiTabs = await this.webviewEl.getTabs();
console.log(`[BrowserApp ${this.webviewId}] Refreshing metadata, getTabs returned:`, apiTabs);
if (!Array.isArray(apiTabs)) return;
let updated = this.#reconcileTabOrderFromApi(apiTabs);
for (const apiTab of apiTabs) {
const tabId = this.#extractApiTabId(apiTab);
const existing = this.#tabs.get(tabId);
if (!existing) {
console.log(`[BrowserApp] Tab ${tabId} from API not found in local tabs; inserting`);
if (this.#upsertTab(apiTab, true)) {
updated = true;
}
continue;
}
// Update title if API has a better one (not empty, not just domain)
if (apiTab.title && apiTab.title.length > 0 && apiTab.title !== existing.title) {
console.log(`[BrowserApp] Updating title for ${tabId}: "${existing.title}" -> "${apiTab.title}"`);
existing.title = apiTab.title;
updated = true;
}
if (apiTab.url && apiTab.url.length > 0 && apiTab.url !== existing.url) {
console.log(`[BrowserApp] Updating URL for ${tabId}: "${existing.url}" -> "${apiTab.url}"`);
existing.url = apiTab.url;
updated = true;
}
if (typeof apiTab.canGoBack === 'boolean' && apiTab.canGoBack !== existing.canGoBack) {
existing.canGoBack = apiTab.canGoBack;
updated = true;
}
if (typeof apiTab.canGoForward === 'boolean' && apiTab.canGoForward !== existing.canGoForward) {
existing.canGoForward = apiTab.canGoForward;
updated = true;
}
// Update favicon if API provides one
const newFavicon = typeof apiTab.faviconDataURI === 'string'
? apiTab.faviconDataURI
: (typeof apiTab.favicon === 'string' ? apiTab.favicon : '');
if (newFavicon && newFavicon.length > 0 && newFavicon !== existing.faviconDataURI) {
console.log(`[BrowserApp] Updating favicon for ${tabId}: ${newFavicon.substring(0, 50)}...`);
existing.faviconDataURI = newFavicon;
updated = true;
}
// Track whether this is the default globe favicon (compat with multiple API field names)
let nextDefaultFavicon = this.#resolveDefaultFaviconFlag(apiTab, existing.isDefaultFavicon ?? true);
// Don't regress to "default" when the tab already has valid favicon data —
// the server may not have resolved the new page's favicon yet even though
// the origin cache (and our local copy) already has the correct icon.
if (nextDefaultFavicon && !existing.isDefaultFavicon && existing.faviconDataURI) {
nextDefaultFavicon = false;
}
if (nextDefaultFavicon !== existing.isDefaultFavicon) {
existing.isDefaultFavicon = nextDefaultFavicon;
updated = true;
}
}
if (updated) {
this._renderTabs();
// Update window title if active tab was updated
const activeTab = this.#getActiveTab();
if (activeTab) {
this._updateWindowTitle(activeTab.title);
this.#setAddressBarUrl(activeTab.url);
this._updateNavButtonStates();
}
}
} catch (err) {
console.warn('[BrowserApp] Failed to refresh tab metadata:', err);
}
// Also try to get favicons separately (some BBX versions need this)
try {
const favicons = await this.webviewEl.getFavicons?.();
console.log(`[BrowserApp ${this.webviewId}] getFavicons returned:`, favicons);
if (favicons && typeof favicons === 'object') {
let faviconUpdated = false;
// Favicons should map by stable targetId/id.
for (const [key, faviconData] of Object.entries(favicons)) {
let matchedTabId = null;
const directId = String(key);
if (this.#tabs.has(directId)) {
matchedTabId = directId;
} else if (faviconData && typeof faviconData === 'object') {
const candidateId = faviconData.id || faviconData.targetId || faviconData.tabId || null;
const normalizedCandidateId = typeof candidateId === 'string' ? candidateId : null;
if (normalizedCandidateId && this.#tabs.has(normalizedCandidateId)) {
matchedTabId = normalizedCandidateId;
}
}
if (matchedTabId) {
const tab = this.#tabs.get(matchedTabId);
const uri = this.#extractFaviconUri(faviconData);
if (tab && uri && uri !== tab.faviconDataURI) {
console.log(`[BrowserApp] Updating favicon for tab ${matchedTabId}: ${uri.substring(0, 50)}...`);
tab.faviconDataURI = uri;
tab.isDefaultFavicon = false;
faviconUpdated = true;
} else if (tab && uri && tab.isDefaultFavicon) {
// Same URI already present but flag was incorrectly set to default
// (e.g. getTabs response raced ahead with isDefaultFavicon:true).
tab.isDefaultFavicon = false;
faviconUpdated = true;
}
continue;
}
console.log(`[BrowserApp ${this.webviewId}] Skipping favicon entry without known tab id`, {
key,
keys: faviconData && typeof faviconData === 'object' ? Object.keys(faviconData) : [],
});
}
if (faviconUpdated) {
this._renderTabs();
}
}
} catch (err) {
// getFavicons may not be available
console.log('[BrowserApp] getFavicons not available or failed:', err.message);
}
}
_updateNavButtonStates() {
const activeTab = this.#getActiveTab();
const debugHistoryUi = globalThis.__BBX_DEBUG_HISTORY_UI__ === true;
const allNavButtons = [
this.ui.navButtons.back, this.ui.navButtons.forward,
this.ui.navButtons.refresh, this.ui.navButtons.stop,
this.ui.navButtons.home, this.ui.navButtons.search,
this.ui.navButtons.favorites, this.ui.navButtons.history
];
if (activeTab) {
const knowsBackState = typeof activeTab.canGoBack === 'boolean';
const knowsForwardState = typeof activeTab.canGoForward === 'boolean';
const isBlankOrError = !activeTab.url || activeTab.url === 'about:blank' || activeTab.url === 'about:error';
const defaultHistoryDisabled = isBlankOrError;
// If capability flags are unavailable, fall back to conservative blank/error defaults.
this.ui.navButtons.back.disabled = knowsBackState ? !activeTab.canGoBack : defaultHistoryDisabled;
this.ui.navButtons.forward.disabled = knowsForwardState ? !activeTab.canGoForward : defaultHistoryDisabled;
if (debugHistoryUi) {
console.log('[BrowserApp][History]', {
webviewId: this.webviewId,
activeTabId: this.#activeTabId,
url: activeTab.url || '',
canGoBack: activeTab.canGoBack,
canGoForward: activeTab.canGoForward,
backDisabled: this.ui.navButtons.back?.disabled ?? null,
forwardDisabled: this.ui.navButtons.forward?.disabled ?? null,
});
}
const isLoading = activeTab.loading;
if (this.ui.navButtons.refresh) {
this.ui.navButtons.refresh.disabled = isBlankOrError || isLoading;
}
if (this.ui.navButtons.stop) {
this.ui.navButtons.stop.disabled = !isLoading;
}
} else {
allNavButtons.forEach(btn => btn && (btn.disabled = true));
if (this.ui.navButtons.stop) this.ui.navButtons.stop.style.display = 'none';
if (this.ui.navButtons.refresh) this.ui.navButtons.refresh.style.display = 'flex';
}
if (this.ui.navButtons.home) this.ui.navButtons.home.disabled = false;
if (this.ui.navButtons.search) this.ui.navButtons.search.disabled = false;
if (this.ui.navButtons.favorites) this.ui.navButtons.favorites.disabled = false;
if (this.ui.navButtons.history) this.ui.navButtons.history.disabled = false;
}
_updateWindowTitle(title) {
const windowTitleBar = this.windowEl.querySelector('.window-title');
if (windowTitleBar) {
const baseTitle = this.appDef.title || 'Internet Browser';
windowTitleBar.textContent = `${title || 'Blank Page'} - ${baseTitle}`;
}
}