-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser-lego.js
More file actions
758 lines (661 loc) · 21.9 KB
/
browser-lego.js
File metadata and controls
758 lines (661 loc) · 21.9 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
/**
* BROWSER CONTAINER
* Left container with iframe browser and navigation controls
*/
let isBrowserInitialized = false;
let currentUrl = 'about:blank';
let historyStack = [];
let historyIndex = -1;
// Search mode state
let currentMode = 'website'; // 'search' or 'website'
let searchResults = [];
let currentQuery = '';
/**
* Initialize Browser container
*/
function initBrowserContainer() {
if (isBrowserInitialized) {
console.log('BROWSER: Already initialized, just showing');
showBrowser();
return;
}
console.log('BROWSER: Initializing container...');
// Find the left container
const container = document.querySelector('.lego-container[data-position="left"]');
if (!container) {
console.error('BROWSER: Container not found');
return;
}
// Clear existing content and create structure
container.innerHTML = `
<div class="browser-wrapper">
<div class="browser-toolbar">
<button class="toolbar-btn" id="browser-back" title="Go back" disabled>←</button>
<button class="toolbar-btn" id="browser-forward" title="Go forward" disabled>→</button>
<button class="toolbar-btn" id="browser-refresh" title="Refresh">⟳</button>
<button class="toolbar-btn" id="browser-home" title="Home">⌂</button>
<div class="browser-address-bar">
<input type="text" id="browser-url" placeholder="Search the web or enter URL..." value="${currentUrl}">
</div>
<button class="toolbar-btn" id="browser-go" title="Search">Search</button>
</div>
<div class="browser-content">
<div class="search-results" id="search-results" style="display: none;">
<!-- Search results will be displayed here -->
</div>
<iframe id="browser-iframe"
src="${currentUrl}"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation"
allow="camera; microphone; geolocation; clipboard-read; clipboard-write">
</iframe>
<div class="browser-loading" id="browser-loading" style="display: none;">
<div class="loading-spinner"></div>
<span>Loading...</span>
</div>
</div>
</div>
`;
// Setup toolbar controls
setupBrowserControls();
// Default homepage: wait for weather to geocode map coordinates, then show location-based news
// Don't run default query immediately - wait for map/weather to be ready
try {
const last = localStorage.getItem('browser:last');
if (last) {
handleSearchOrNavigate(last);
} else {
// Wait for weather to geocode the default map coordinates (same as weather does)
// Weather uses default coordinates on init, so we wait for it to finish geocoding
let retries = 0;
const maxRetries = 10; // Try for up to 5 seconds (10 * 500ms)
const checkLocation = () => {
if (window.WeatherContainer && typeof window.WeatherContainer.getCurrentLocation === 'function') {
const location = window.WeatherContainer.getCurrentLocation();
if (location && location.trim().length > 0) {
console.log('BROWSER: Got location from weather, searching news:', location);
searchLocationNews(location);
return;
}
}
// Retry if weather hasn't geocoded yet
retries++;
if (retries < maxRetries) {
setTimeout(checkLocation, 500); // Check every 500ms
} else {
// Fallback after all retries - should rarely happen
console.log('BROWSER: Weather geocoding taking too long, using default');
searchWithPerplexity('top 20 news stories today');
}
};
// Start checking after a short delay to let weather start
setTimeout(checkLocation, 500);
}
} catch {}
isBrowserInitialized = true;
console.log('BROWSER: Initialized successfully');
}
/**
* Setup browser controls
*/
function setupBrowserControls() {
// Back button
document.getElementById('browser-back').addEventListener('click', function() {
goBack();
});
// Forward button
document.getElementById('browser-forward').addEventListener('click', function() {
goForward();
});
// Refresh button
document.getElementById('browser-refresh').addEventListener('click', function() {
refreshPage();
});
// Home button - use current map location if available
document.getElementById('browser-home').addEventListener('click', function() {
// Try to get location from weather (which has map coordinates)
if (window.WeatherContainer && typeof window.WeatherContainer.getCurrentLocation === 'function') {
const location = window.WeatherContainer.getCurrentLocation();
if (location) {
document.getElementById('browser-url').value = location;
searchLocationNews(location);
} else {
// Fallback to generic news
const q = 'top news today';
document.getElementById('browser-url').value = q;
searchWithPerplexity(q);
}
} else {
const q = 'top news today';
document.getElementById('browser-url').value = q;
searchWithPerplexity(q);
}
});
// Search button
document.getElementById('browser-go').addEventListener('click', function() {
const query = document.getElementById('browser-url').value.trim();
if (query) {
handleSearchOrNavigate(query);
}
});
// Address bar - handle Enter key
document.getElementById('browser-url').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
const query = this.value.trim();
if (query) {
handleSearchOrNavigate(query);
}
}
});
// iframe load events
const iframe = document.getElementById('browser-iframe');
if (iframe) {
iframe.addEventListener('load', function() {
hideLoading();
updateNavigationButtons();
console.log('BROWSER: Page loaded');
});
iframe.addEventListener('error', function(e) {
hideLoading();
console.error('BROWSER: Failed to load page');
});
iframe.addEventListener('load', function() {
hideLoading();
updateNavigationButtons();
console.log('BROWSER: Page loaded');
});
}
}
/**
* Handle search or navigation based on input
*/
function handleSearchOrNavigate(input) {
// Check if input looks like a URL
if (isUrl(input)) {
// Direct URL navigation
navigateTo(input);
} else {
// Search with Perplexity
searchWithPerplexity(input);
}
}
/**
* Check if input looks like a URL
*/
function isUrl(input) {
try {
// Check if it's a valid URL
new URL(input.startsWith('http') ? input : 'https://' + input);
return true;
} catch (e) {
// Check if it looks like a domain (contains dots and no spaces)
return input.includes('.') && !input.includes(' ');
}
}
/**
* Search for location-based news (5 top stories)
*/
function searchLocationNews(location) {
if (!location) {
searchWithPerplexity('top 5 news stories today');
return;
}
// Create query for location-based news
const query = `top 5 news stories for ${location}`;
console.log('BROWSER: Searching location news for:', location);
document.getElementById('browser-url').value = location;
searchWithPerplexity(query);
}
/**
* Update news based on map center coordinates
* Called automatically when map center changes
*/
function updateFromMap(lat, lng) {
console.log('BROWSER: Updating from map center:', lat, lng);
// Wait for weather to geocode the location first (since it's called from map too)
// Then get the geocoded address and use it for news
setTimeout(() => {
if (window.WeatherContainer && typeof window.WeatherContainer.getCurrentLocation === 'function') {
const location = window.WeatherContainer.getCurrentLocation();
if (location) {
searchLocationNews(location);
} else {
// If weather hasn't geocoded yet, wait a bit more
setTimeout(() => {
const loc = window.WeatherContainer.getCurrentLocation();
if (loc) {
searchLocationNews(loc);
}
}, 500);
}
}
}, 600); // Wait for weather geocoding to complete
}
/**
* Search with Perplexity
*/
async function searchWithPerplexity(query) {
console.log('BROWSER: Searching with Perplexity:', query);
showLoading();
currentQuery = query;
currentMode = 'search';
try {
// Call Perplexity API (using existing AI module)
const aiResponse = await AI.getAIResponse(query);
// Handle both old format (string) and new format (object with content and citations)
const response = typeof aiResponse === 'string' ? aiResponse : aiResponse.content;
const citations = typeof aiResponse === 'object' && aiResponse.citations ? aiResponse.citations : [];
// Parse response and extract search results
const results = parsePerplexityResponse(response, citations);
searchResults = results;
// Display search results
displaySearchResults(results);
hideLoading();
// Add to history
addToHistory(`search:${query}`);
} catch (error) {
console.error('BROWSER: Search failed:', error);
hideLoading();
showError('Search failed. Please try again.');
}
}
/**
* Parse Perplexity response to extract search results
*/
function parsePerplexityResponse(response, citations = []) {
// Extract information from Perplexity's response and create useful results
const results = [];
// Build citation map: citation number -> URL
const citationMap = {};
if (Array.isArray(citations)) {
citations.forEach((citation, index) => {
// Citations might be URLs directly, or objects with url property
const url = typeof citation === 'string' ? citation : (citation.url || citation.href || '');
if (url) {
citationMap[index + 1] = url; // [1] -> index 0, [2] -> index 1, etc.
}
});
}
// Also try to extract citations from response text (if they appear at the end)
const citationMatches = response.match(/\[(\d+)\]:\s*(https?:\/\/[^\s\)]+)/g);
if (citationMatches) {
citationMatches.forEach(match => {
const numMatch = match.match(/\[(\d+)\]:/);
const urlMatch = match.match(/https?:\/\/[^\s\)]+/);
if (numMatch && urlMatch) {
citationMap[parseInt(numMatch[1])] = urlMatch[0];
}
});
}
// Split response into sections and create results
const sections = response.split('\n\n').filter(section => section.trim().length > 0);
sections.forEach((section, index) => {
if (section.trim().length > 50) { // Only include substantial sections
const lines = section.split('\n');
// Extract citation numbers from the original line before cleaning
const originalLine = lines[0];
const citationNumbers = [];
const citationMatches = originalLine.match(/\[(\d+)\]/g);
if (citationMatches) {
citationMatches.forEach(match => {
const num = parseInt(match.replace(/[\[\]]/g, ''));
if (num) citationNumbers.push(num);
});
}
// Get the first available citation URL
let sourceUrl = null;
for (const num of citationNumbers) {
if (citationMap[num]) {
sourceUrl = citationMap[num];
break;
}
}
// Clean title: remove markdown bold (**), citation numbers ([1], [2][4], etc.)
let title = lines[0]
.replace(/\*\*/g, '') // Remove all **
.replace(/\[\d+\]/g, '') // Remove [1], [2], etc. (multiple passes handle [2][4])
.replace(/\[\d+\]/g, '') // Second pass for nested citations
.trim();
// Clean snippet: take text after the dash (if present) and limit length
let snippet = lines.slice(1).join(' ').trim();
if (!snippet && lines.length > 0) {
// If no separate snippet, extract from title line after the dash
const dashIndex = lines[0].indexOf(' - ');
if (dashIndex > -1) {
snippet = lines[0].substring(dashIndex + 3);
}
}
// Remove markdown from snippet too
snippet = snippet
.replace(/\*\*/g, '')
.replace(/\[\d+\]/g, '') // Remove citation numbers
.replace(/\[\d+\]/g, '') // Second pass for nested citations
.trim();
// Limit snippet to 120 characters
if (snippet.length > 120) {
snippet = snippet.substring(0, 120).trim() + '...';
}
// Use source URL if available, otherwise fallback to Google search
const resultUrl = sourceUrl || `https://www.google.com/search?q=${encodeURIComponent(currentQuery + ' ' + title.substring(0, 30))}`;
// Create a result that opens in new tab since iframe has restrictions
results.push({
title: title || `Search Result ${index + 1}`,
url: resultUrl,
snippet: snippet,
isExternal: true,
citationNumber: citationNumbers[0] || null
});
}
});
// If no good sections found, create a general search result
if (results.length === 0) {
results.push({
title: `Search Results for "${currentQuery}"`,
url: `https://www.google.com/search?q=${encodeURIComponent(currentQuery)}`,
snippet: "Click to search on Google for more detailed results.",
isExternal: true
});
}
return results;
}
/**
* Display search results in Google-style format
*/
function displaySearchResults(results) {
const searchContainer = document.getElementById('search-results');
const iframe = document.getElementById('browser-iframe');
if (!searchContainer || !iframe) return;
// Hide iframe, show search results
iframe.style.display = 'none';
searchContainer.style.display = 'block';
// Generate HTML for search results
const resultsHtml = results.map((result, index) => {
// Extract domain from URL for display, or show a generic label
let urlDisplay = 'Search result';
if (!result.url.includes('google.com/search')) {
try {
const urlObj = new URL(result.url);
urlDisplay = urlObj.hostname.replace('www.', '');
} catch (e) {
urlDisplay = 'Search result';
}
}
// Escape HTML in title and snippet for safety
const escapeHtml = (str) => {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
const safeUrl = escapeHtml(result.url);
const safeTitle = escapeHtml(result.title);
const safeSnippet = escapeHtml(result.snippet);
const safeUrlDisplay = escapeHtml(urlDisplay);
return `
<div class="search-result" data-url="${safeUrl}">
<h3 class="result-title">
<a href="${safeUrl}" target="_blank" onclick="handleResultClick('${safeUrl}', ${result.isExternal}); return false;">${safeTitle}</a>
</h3>
<div class="result-url">
<a href="${safeUrl}" target="_blank" onclick="handleResultClick('${safeUrl}', ${result.isExternal}); return false;">${safeUrlDisplay}</a>
</div>
<div class="result-snippet">${safeSnippet}</div>
</div>
`;
}).join('');
searchContainer.innerHTML = `
<div class="search-header">
<div class="search-info">About ${results.length} results for "${currentQuery}"</div>
</div>
<div class="results-list">
${resultsHtml}
</div>
`;
console.log('BROWSER: Displayed search results');
}
/**
* Handle search result clicks
*/
function handleResultClick(url, isExternal) {
console.log('BROWSER: Handling result click:', url, 'External:', isExternal);
if (isExternal) {
// Open in new tab for external links
window.open(url, '_blank');
} else {
// Try to open in iframe
openSearchResult(url);
}
}
/**
* Open a search result in the iframe
*/
function openSearchResult(url) {
console.log('BROWSER: Opening search result:', url);
// Switch to website mode
currentMode = 'website';
// Hide search results, show iframe
const searchContainer = document.getElementById('search-results');
const iframe = document.getElementById('browser-iframe');
if (searchContainer && iframe) {
searchContainer.style.display = 'none';
iframe.style.display = 'block';
// Navigate to the URL
navigateTo(url);
}
}
/**
* Navigate to a URL
*/
function navigateTo(url) {
if (!url) return;
// Ensure URL has protocol
if (!url.startsWith('http://') && !url.startsWith('https://')) {
if (url.includes('.') && !url.includes(' ')) {
url = 'https://' + url;
} else {
// Treat as search
searchWithPerplexity(url);
return;
}
}
currentUrl = url;
currentMode = 'website';
const iframe = document.getElementById('browser-iframe');
if (iframe) {
showLoading();
iframe.src = url;
document.getElementById('browser-url').value = url;
addToHistory(url);
}
console.log('BROWSER: Navigating to', url);
}
/**
* Navigate to URL (with validation)
*/
function navigateToUrl(url) {
try {
// Basic URL validation
new URL(url.startsWith('http') ? url : 'https://' + url);
navigateTo(url);
} catch (e) {
// If URL is invalid, treat as search
navigateTo(url);
}
}
/**
* Go back in history
*/
function goBack() {
if (historyIndex > 0) {
historyIndex--;
const historyItem = historyStack[historyIndex];
if (historyItem.startsWith('search:')) {
// Go back to search results
const query = historyItem.replace('search:', '');
currentQuery = query;
currentMode = 'search';
displaySearchResults(searchResults);
document.getElementById('browser-url').value = query;
} else {
// Go back to website
currentUrl = historyItem;
currentMode = 'website';
const iframe = document.getElementById('browser-iframe');
const searchContainer = document.getElementById('search-results');
if (iframe && searchContainer) {
showLoading();
iframe.src = historyItem;
iframe.style.display = 'block';
searchContainer.style.display = 'none';
document.getElementById('browser-url').value = historyItem;
}
}
updateNavigationButtons();
console.log('BROWSER: Going back to', historyItem);
}
}
/**
* Go forward in history
*/
function goForward() {
if (historyIndex < historyStack.length - 1) {
historyIndex++;
const historyItem = historyStack[historyIndex];
if (historyItem.startsWith('search:')) {
// Go forward to search results
const query = historyItem.replace('search:', '');
currentQuery = query;
currentMode = 'search';
displaySearchResults(searchResults);
document.getElementById('browser-url').value = query;
} else {
// Go forward to website
currentUrl = historyItem;
currentMode = 'website';
const iframe = document.getElementById('browser-iframe');
const searchContainer = document.getElementById('search-results');
if (iframe && searchContainer) {
showLoading();
iframe.src = historyItem;
iframe.style.display = 'block';
searchContainer.style.display = 'none';
document.getElementById('browser-url').value = historyItem;
}
}
updateNavigationButtons();
console.log('BROWSER: Going forward to', historyItem);
}
}
/**
* Refresh current page
*/
function refreshPage() {
const iframe = document.getElementById('browser-iframe');
if (iframe) {
showLoading();
iframe.src = iframe.src; // Reload iframe
console.log('BROWSER: Refreshing page');
}
}
/**
* Add URL to history
*/
function addToHistory(url) {
// Remove any forward history if we're not at the end
if (historyIndex < historyStack.length - 1) {
historyStack = historyStack.slice(0, historyIndex + 1);
}
historyStack.push(url);
historyIndex = historyStack.length - 1;
// Limit history size
if (historyStack.length > 50) {
historyStack.shift();
historyIndex--;
}
updateNavigationButtons();
}
/**
* Update navigation button states
*/
function updateNavigationButtons() {
const backBtn = document.getElementById('browser-back');
const forwardBtn = document.getElementById('browser-forward');
if (backBtn) {
backBtn.disabled = historyIndex <= 0;
}
if (forwardBtn) {
forwardBtn.disabled = historyIndex >= historyStack.length - 1;
}
}
/**
* Show loading indicator
*/
function showLoading() {
const loading = document.getElementById('browser-loading');
if (loading) {
loading.style.display = 'flex';
}
}
/**
* Hide loading indicator
*/
function hideLoading() {
const loading = document.getElementById('browser-loading');
if (loading) {
loading.style.display = 'none';
}
}
/**
* Show error message
*/
function showError(message) {
console.error('BROWSER ERROR:', message);
// For now, just log to console - you can add UI error display later
}
/**
* Show browser
*/
function showBrowser() {
if (!isBrowserInitialized) {
initBrowserContainer();
return;
}
// Ensure iframe is properly sized
setTimeout(() => {
const container = document.querySelector('.lego-container[data-position="left"]');
if (container) {
const iframe = document.getElementById('browser-iframe');
if (iframe) {
// Force iframe to refresh if needed
if (iframe.src !== currentUrl) {
iframe.src = currentUrl;
}
}
}
}, 100);
console.log('BROWSER: Showing container');
}
/**
* Hide browser
*/
function hideBrowser() {
console.log('BROWSER: Hiding container');
}
// Export functions for use in main script
if (typeof window !== 'undefined') {
window.BrowserContainer = {
init: initBrowserContainer,
show: showBrowser,
hide: hideBrowser,
navigateTo: navigateTo,
searchWithPerplexity: searchWithPerplexity,
searchLocationNews: searchLocationNews,
updateFromMap: updateFromMap,
openSearchResult: openSearchResult,
handleResultClick: handleResultClick,
getCurrentUrl: () => currentUrl,
getCurrentMode: () => currentMode,
isInitialized: () => isBrowserInitialized
};
}