-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontent.js
More file actions
1306 lines (1103 loc) · 45.9 KB
/
content.js
File metadata and controls
1306 lines (1103 loc) · 45.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
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
// content.js
// --- Configuration ---
const MAX_SUMMARY_WORDS = 10; // Max words for the summary in the nav bar
const OBSERVER_DEBOUNCE_TIME = 1000; // Milliseconds to wait after DOM changes before updating nav
// --- State ---
let navBar;
let searchInput;
let allNavItems = []; // Store all nav items for filtering
let searchTimeout;
let lastProcessedQueryId = -1;
let lastProcessedResponseId = -1;
let observerTimeout;
let currentProvider; // Current AI provider instance
let sessionQueries = []; // Persistent storage for queries in current session
let isLoading = false; // Loading state for data refresh
let currentUrl = window.location.href; // Track current URL for change detection
let currentNavigationIndex = -1; // Track currently highlighted nav item for keyboard navigation
let keyboardNavigationActive = false; // Track if keyboard navigation is active
// --- Focus Mode State ---
let focusModeEnabled = true; // Master toggle for focus mode
let sidebarCollapsedByFocus = false; // Track if sidebar was auto-collapsed by focus
let sidebarWasCollapsedManually = false; // Track manual collapse state before focus
let focusBlurTimeout = null; // Timeout for handling blur events with delay
let attachedInputElements = new Set(); // Track attached input listeners
// --- Loading State Management ---
/**
* Shows loading indicator in the navigation bar
*/
function showLoadingState() {
if (!navBar || isLoading) return;
isLoading = true;
// Clear existing nav items
const existingNavItems = navBar.querySelectorAll('.nav-item');
existingNavItems.forEach(item => item.remove());
allNavItems = [];
resetNavigationIndex(); // Reset keyboard navigation when clearing items
// Create loading indicator
const loadingContainer = document.createElement('div');
loadingContainer.className = 'nav-loading-container';
loadingContainer.innerHTML = `
<div class="nav-loading-spinner"></div>
<div class="nav-loading-text">Loading questions...</div>
`;
navBar.appendChild(loadingContainer);
}
/**
* Hides loading indicator and restores normal navigation
*/
function hideLoadingState() {
if (!navBar || !isLoading) return;
const loadingContainer = navBar.querySelector('.nav-loading-container');
if (loadingContainer) {
loadingContainer.remove();
}
isLoading = false;
}
/**
* Handles focus mode toggle button click
*/
function handleFocusModeToggle(event) {
event.preventDefault();
event.stopPropagation();
const focusModeBtn = document.getElementById('ai-nav-focus-mode-btn');
if (!focusModeBtn) return;
// Toggle focus mode
toggleFocusMode(!focusModeEnabled);
// Update button visual state
if (focusModeEnabled) {
focusModeBtn.classList.add('active');
focusModeBtn.title = 'Focus Mode: ON - Sidebar auto-hides when typing';
} else {
focusModeBtn.classList.remove('active');
focusModeBtn.title = 'Focus Mode: OFF - Click to enable auto-hide when typing';
}
console.log(`AI Navigator: Focus mode ${focusModeEnabled ? 'enabled' : 'disabled'} by user`);
}
/**
* Handles refresh button click with loading state and error handling
*/
function handleRefreshClick(event) {
event.preventDefault();
event.stopPropagation();
const refreshBtn = document.getElementById('ai-nav-refresh-btn');
if (!refreshBtn) return;
// Clear search bar if it has content
if (searchInput && searchInput.value.trim()) {
clearSearch();
console.log('AI Navigator: Search cleared during refresh');
}
// Disable button and show loading state
refreshBtn.disabled = true;
refreshBtn.classList.add('loading');
console.log('AI Navigator: Refresh button clicked, starting data refresh...');
try {
refreshData();
// Re-enable button after refresh completes
setTimeout(() => {
refreshBtn.disabled = false;
refreshBtn.classList.remove('loading');
console.log('AI Navigator: Refresh button re-enabled');
}, 600); // Slightly longer than refreshData delay to ensure completion
} catch (error) {
console.error('AI Navigator: Error during refresh:', error);
// Re-enable button even if refresh fails
refreshBtn.disabled = false;
refreshBtn.classList.remove('loading');
// Could show error feedback here in the future
console.warn('AI Navigator: Refresh operation failed, button re-enabled');
}
}
/**
* Refreshes all data - clears session and reprocesses page
*/
function refreshData() {
console.log('AI Navigator: Refreshing data...');
showLoadingState();
// Clear session data
sessionQueries = [];
// Reset focus mode state
resetFocusModeState();
// Process with a small delay to show loading state
setTimeout(() => {
try {
processChatElements();
hideLoadingState();
// Reattach focus mode listeners after refresh
setupFocusMode();
console.log('AI Navigator: Data refresh completed');
} catch (error) {
hideLoadingState();
console.error('AI Navigator: Error during data refresh:', error);
throw error; // Re-throw to be caught by handleRefreshClick
}
}, 500);
}
// --- Page Change Detection ---
/**
* Detects URL changes and refreshes data accordingly
*/
function handleUrlChange() {
const newUrl = window.location.href;
if (newUrl !== currentUrl) {
console.log(`AI Navigator: URL changed from ${currentUrl} to ${newUrl}`);
currentUrl = newUrl;
// Check if we're still on a supported provider page
const providerFactory = new ProviderFactory();
const newProvider = providerFactory.getCurrentProvider();
if (newProvider && newProvider.name === currentProvider?.name) {
// Same provider, different page - refresh data
refreshData();
} else if (newProvider) {
// Different provider - reinitialize
console.log(`AI Navigator: Provider changed to ${newProvider.name}, reinitializing...`);
currentProvider = newProvider;
refreshData();
} else {
// No longer on supported page - could hide navbar
console.log('AI Navigator: No longer on supported page');
}
}
}
/**
* Sets up page change detection
*/
function setupPageChangeDetection() {
// Listen for popstate events (back/forward navigation)
window.addEventListener('popstate', handleUrlChange);
// Listen for pushstate/replacestate (programmatic navigation)
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function() {
originalPushState.apply(history, arguments);
setTimeout(handleUrlChange, 100); // Small delay to let page update
};
history.replaceState = function() {
originalReplaceState.apply(history, arguments);
setTimeout(handleUrlChange, 100);
};
// Listen for visibility change (tab switching)
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
// Tab became visible - check for URL changes and refresh
setTimeout(() => {
handleUrlChange();
// Also refresh data in case content changed while tab was hidden
if (currentProvider) {
refreshData();
}
}, 500);
}
});
console.log('AI Navigator: Page change detection setup complete');
}
// --- Session Management ---
/**
* Loads persisted queries (in-memory only, resets on page reload)
* @returns {Array} Array of stored query objects
*/
function loadSessionQueries() {
// Return empty array - fresh start on each page load
return [];
}
/**
* Saves current queries (in-memory only, no persistence)
*/
function saveSessionQueries() {
// No-op - we don't persist to storage to avoid stale data
// Data is kept in memory only during the current page session
}
/**
* Adds a new query to the session if it doesn't already exist
* @param {Object} queryData - Query data object {id, text, element, index}
*/
function addQueryToSession(queryData) {
// Check if query already exists (by ID or text)
const existingIndex = sessionQueries.findIndex(q =>
q.id === queryData.id || q.text === queryData.text
);
if (existingIndex === -1) {
sessionQueries.push(queryData);
saveSessionQueries();
return true; // New query added
}
return false; // Query already existed
}
/**
* Validates session queries against current DOM and removes inactive ones
* @returns {Array} Array of validated and active query objects
*/
function validateSessionQueries() {
if (!currentProvider) return sessionQueries;
const selectors = currentProvider.getSelectors();
const currentDOMQueries = document.querySelectorAll(selectors.queries);
const validQueries = [];
let removedCount = 0;
console.log(`AI Navigator: Validating ${sessionQueries.length} stored queries against ${currentDOMQueries.length} DOM queries`);
sessionQueries.forEach((queryData, index) => {
let isValid = false;
let targetElement = null;
// First try to find by stored element ID
if (queryData.elementId) {
targetElement = document.getElementById(queryData.elementId);
if (targetElement) {
// Verify the element still contains the expected text
try {
const currentText = currentProvider.extractTextContent(targetElement);
if (currentText && currentText.trim() === queryData.text.trim()) {
isValid = true;
}
} catch (error) {
// Element exists but can't extract text - might be broken
console.warn(`AI Navigator: Could not extract text from stored element ${queryData.elementId}`);
}
}
}
// If not found by ID, try to find by content matching
if (!isValid) {
for (const element of currentDOMQueries) {
try {
const elementText = currentProvider.extractTextContent(element);
if (elementText && elementText.trim() === queryData.text.trim()) {
targetElement = element;
// Update the element ID reference if it changed
if (element.id && element.id !== queryData.elementId) {
queryData.elementId = element.id;
}
isValid = true;
break;
}
} catch (error) {
// Continue searching
}
}
}
if (isValid) {
validQueries.push(queryData);
} else {
removedCount++;
console.log(`AI Navigator: Removed inactive query: ${queryData.text.substring(0, 50)}...`);
}
});
if (removedCount > 0) {
console.log(`AI Navigator: Validation complete - removed ${removedCount} inactive queries, ${validQueries.length} remain active`);
// Update session queries with only valid ones
sessionQueries = validQueries;
// Re-index the valid queries
sessionQueries.forEach((query, index) => {
query.index = index;
});
} else {
console.log(`AI Navigator: Validation complete - all ${validQueries.length} queries are still active`);
}
return validQueries;
}
/**
* Rebuilds navigation from session data and current DOM elements
*/
function rebuildNavigationFromSession() {
if (!navBar) return;
// Clear existing nav items
const existingNavItems = navBar.querySelectorAll('.nav-item');
existingNavItems.forEach(item => item.remove());
allNavItems = [];
// Validate queries first to remove any broken/inactive ones
const validQueries = validateSessionQueries();
// Rebuild from validated session data
validQueries.forEach((queryData, index) => {
// Try to find the element in the current DOM
let targetElement = null;
// First try to find by stored element reference (if still in DOM)
if (queryData.elementId) {
targetElement = document.getElementById(queryData.elementId);
}
// If not found, try to find by content matching
if (!targetElement) {
const selectors = currentProvider.getSelectors();
const queryElements = document.querySelectorAll(selectors.queries);
for (const element of queryElements) {
try {
const elementText = currentProvider.extractTextContent(element);
if (elementText && elementText.trim() === queryData.text.trim()) {
targetElement = element;
// Update element ID if it changed
if (element.id && element.id !== queryData.elementId) {
queryData.elementId = element.id;
}
break;
}
} catch (error) {
// Continue searching
}
}
}
// Create a placeholder element if original not found (for virtual scrolling)
if (!targetElement) {
targetElement = createPlaceholderElement(queryData);
}
const summary = generateSummary(queryData.text);
addNavItem(`<strong>${index + 1}.</strong> ${summary}`, 'query', targetElement, `session-query-${index}`);
});
}
/**
* Creates a placeholder element for queries not currently in DOM (virtual scrolling)
* @param {Object} queryData - Query data object
* @returns {HTMLElement} Placeholder element
*/
function createPlaceholderElement(queryData) {
const placeholder = document.createElement('div');
placeholder.className = 'ai-nav-placeholder';
placeholder.dataset.queryText = queryData.text;
placeholder.dataset.queryId = queryData.id;
placeholder.style.display = 'none'; // Hidden placeholder
document.body.appendChild(placeholder);
// Add click handler to scroll to query (for AI Studio virtual scrolling)
placeholder.addEventListener('click', () => {
// For AI Studio, we might need to trigger scrolling to make the element visible
console.log(`AI Navigator: Attempting to navigate to: ${queryData.text.substring(0, 50)}...`);
console.warn('AI Navigator: This question may not be currently visible due to virtual scrolling');
// This could be enhanced with provider-specific navigation logic
});
return placeholder;
}
// --- Core Functions ---
/**
* Creates and injects the navigation bar into the page.
*/
function createNavBar() {
if (document.getElementById('ai-nav-bar')) {
return; // Nav bar already exists
}
if (!currentProvider) {
console.error('AI Navigator: No provider found for current page');
return;
}
const layoutConfig = currentProvider.getLayoutConfig();
navBar = document.createElement('div');
navBar.id = 'ai-nav-bar';
navBar.classList.add('collapsed'); // Start with sidebar collapsed by default
navBar.style.top = `${layoutConfig.topOffset}px`;
navBar.style.height = `calc(100vh - ${layoutConfig.topOffset}px)`;
// Create header with provider-specific title and control buttons
const header = document.createElement('h3');
header.innerHTML = `<div class="header-buttons">
<button id="ai-nav-focus-mode-btn" title="Toggle Focus Mode (Auto-hide sidebar when typing)" aria-label="Toggle Focus Mode" class="${focusModeEnabled ? 'active' : ''}">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg>
</button>
<button id="ai-nav-refresh-btn" title="Refresh Chat Navigation" aria-label="Refresh Chat Navigation">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="23 4 23 10 17 10"></polyline>
<polyline points="1 20 1 14 7 14"></polyline>
<path d="m20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path>
</svg>
</button>
</div>${currentProvider.getNavTitle()} <span id="ai-nav-collapse-btn" title="Collapse Navigation">»</span>`;
navBar.appendChild(header);
// Create search container
const searchContainer = document.createElement('div');
searchContainer.className = 'search-container';
searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.className = 'search-input';
searchInput.placeholder = 'Search questions...';
const searchClear = document.createElement('div');
searchClear.className = 'search-clear';
searchClear.innerHTML = '×';
searchClear.style.display = 'none';
searchContainer.appendChild(searchInput);
searchContainer.appendChild(searchClear);
navBar.appendChild(searchContainer);
document.body.appendChild(navBar);
document.body.classList.add('ai-nav-collapsed'); // Start with body class for collapsed state
// Initialize search functionality
searchInput.addEventListener('input', handleSearch);
searchClear.addEventListener('click', clearSearch);
const expandBtn = document.createElement('button');
expandBtn.id = 'ai-nav-expand-btn';
expandBtn.title = 'Expand Navigation';
expandBtn.innerHTML = '«';
expandBtn.classList.add('initial-glow'); // Add glow animation on initial load
document.body.appendChild(expandBtn);
// Remove glow after animation completes (2s duration * 3 iterations + 0.5s delay = 6.5s)
setTimeout(() => {
expandBtn.classList.remove('initial-glow');
}, 6500);
const collapseBtn = document.getElementById('ai-nav-collapse-btn');
const refreshBtn = document.getElementById('ai-nav-refresh-btn');
const focusModeBtn = document.getElementById('ai-nav-focus-mode-btn');
if (navBar && collapseBtn && expandBtn) {
collapseBtn.addEventListener('click', toggleNav);
expandBtn.addEventListener('click', (e) => {
expandBtn.classList.remove('initial-glow'); // Remove glow on first interaction
toggleNav();
});
} else {
console.error('AI Navigator: Could not find all necessary elements for collapse/expand functionality.');
}
if (refreshBtn) {
refreshBtn.addEventListener('click', handleRefreshClick);
} else {
console.error('AI Navigator: Could not find refresh button element.');
}
if (focusModeBtn) {
focusModeBtn.addEventListener('click', handleFocusModeToggle);
} else {
console.error('AI Navigator: Could not find focus mode button element.');
}
adjustMainContentLayout(); // Adjust layout after adding nav bar
}
/**
* Generates a concise summary from text.
* @param {string} text - The text to summarize.
* @returns {string} A short summary.
*/
/**
* Adjusts the main content area to make space for the sidebar.
*/
/**
* Toggles the collapsed/expanded state of the navigation bar.
*/
function toggleNav() {
if (!navBar) return;
const wasCollapsed = navBar.classList.contains('collapsed');
// If expanding and sidebar was auto-collapsed by focus, clear focus mode state
if (wasCollapsed && sidebarCollapsedByFocus) {
sidebarCollapsedByFocus = false;
console.log('AI Navigator: Manual expand - clearing focus mode auto-collapse state');
}
navBar.classList.toggle('collapsed');
document.body.classList.toggle('ai-nav-collapsed');
adjustMainContentLayout(); // Re-adjust margin after toggling
}
/**
* Adjusts the main content area to make space for the sidebar.
* @param {number} retryCount - Number of times to retry finding the element
*/
function adjustMainContentLayout(retryCount = 0) {
if (!currentProvider) return;
const layoutConfig = currentProvider.getLayoutConfig();
const mainContentMargin = layoutConfig.navBarWidth + layoutConfig.gap + 'px';
// Use provider-specific main content selectors
const mainContentSelectors = currentProvider.getSelectors().mainContent;
let mainContentArea = null;
for (const selector of mainContentSelectors) {
mainContentArea = document.querySelector(selector);
if (mainContentArea) {
console.log(`AI Navigator: Found main content area using selector: ${selector}`, mainContentArea);
break;
}
}
if (mainContentArea) {
if (navBar && navBar.classList.contains('collapsed')) {
mainContentArea.style.marginRight = '0px';
console.log('AI Navigator: Navbar collapsed, removed margin-right from main content area.');
} else {
mainContentArea.style.marginRight = mainContentMargin;
console.log('AI Navigator: Applied margin-right to main content area:', mainContentArea);
}
} else {
// Retry mechanism for when DOM isn't fully loaded yet
if (retryCount < 3) {
console.log(`AI Navigator: Main content area not found for ${currentProvider.name}, retrying in 1 second... (attempt ${retryCount + 1}/3)`);
setTimeout(() => {
adjustMainContentLayout(retryCount + 1);
}, 1000);
} else {
// Final attempt - try some common fallback selectors
const fallbackSelectors = [
'body > div:first-child',
'[role="main"]',
'main',
'.main-content',
'.content',
'#app',
'#root'
];
for (const selector of fallbackSelectors) {
mainContentArea = document.querySelector(selector);
if (mainContentArea) {
console.log(`AI Navigator: Found fallback content area using: ${selector}`, mainContentArea);
if (navBar && !navBar.classList.contains('collapsed')) {
mainContentArea.style.marginRight = mainContentMargin;
console.log('AI Navigator: Applied margin-right to fallback content area');
}
return;
}
}
console.warn(`AI Navigator: Could not identify ${currentProvider.name} main content area to adjust layout after 3 attempts. Sidebar will still work but layout may not be optimal.`);
}
}
}
/**
* Generates a concise summary from text.
* @param {string} text - The text to summarize.
* @returns {string} A short summary.
*/
function generateSummary(text) {
if (!text) return 'No content';
const words = text.trim().split(/\s+/);
if (words.length > MAX_SUMMARY_WORDS) {
return words.slice(0, MAX_SUMMARY_WORDS).join(' ') + '...';
}
return words.join(' ');
}
/**
* Adds a navigation item to the bar.
* @param {string} summary - The text summary for the nav item.
* @param {string} type - 'query' or 'response'.
* @param {HTMLElement} targetElement - The element to scroll to.
* @param {string} elementId - The ID of the target element.
*/
function addNavItem(summary, type, targetElement, elementId) {
if (!navBar || !targetElement) return;
// Ensure target element has an ID for scrolling, or assign one
if (!targetElement.id) {
targetElement.id = `ai-nav-target-${type}-${elementId.replace(/[^a-zA-Z0-9-_]/g, '')}`;
}
const navItemId = `nav-item-for-${targetElement.id}`;
// Avoid adding duplicate nav items
if (document.getElementById(navItemId)) {
return;
}
const fullText = targetElement.innerText || '';
const navItem = document.createElement('div');
navItem.classList.add('nav-item', type);
navItem.innerHTML = summary;
navItem.title = fullText.substring(0, 200) + (fullText.length > 200 ? '...' : ''); // Full text on hover
navItem.id = navItemId;
// Store full text for searching
navItem.dataset.fullText = fullText.toLowerCase();
navItem.dataset.summary = summary.toLowerCase();
navItem.addEventListener('click', () => {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Optional: Highlight active item (implement with an 'active' class)
document.querySelectorAll('#ai-nav-bar .nav-item').forEach(item => item.classList.remove('active'));
navItem.classList.add('active');
});
navBar.appendChild(navItem);
allNavItems.push(navItem); // Store for filtering
}
/**
* Finds and processes all user queries on the page using the current provider.
*/
function processChatElements() {
console.log(`AI Navigator: Processing chat elements for ${currentProvider?.name || 'unknown provider'}...`);
if (!currentProvider) {
console.error('AI Navigator: No provider available for processing chat elements');
return;
}
const selectors = currentProvider.getSelectors();
// --- Process User Queries ---
const queryElements = document.querySelectorAll(selectors.queries);
let newQueriesFound = false;
queryElements.forEach((queryElement, index) => {
try {
const textContent = currentProvider.extractTextContent(queryElement);
if (textContent && textContent.trim()) {
// Create query data object
const queryId = queryElement.id || `query-${Date.now()}-${index}`;
const queryData = {
id: queryId,
text: textContent.trim(),
elementId: queryElement.id,
timestamp: Date.now(),
index: sessionQueries.length
};
// Ensure element has an ID for future reference
if (!queryElement.id) {
queryElement.id = queryId;
queryData.elementId = queryId;
}
// Add to session if it's new
if (addQueryToSession(queryData)) {
newQueriesFound = true;
console.log(`AI Navigator: Added new query to session: ${textContent.substring(0, 50)}...`);
}
} else {
console.warn(`AI Navigator: Could not extract text content for query element:`, queryElement);
}
} catch (error) {
console.warn(`AI Navigator: Error processing query element:`, error, queryElement);
}
});
// Rebuild navigation from complete session data (includes validation)
rebuildNavigationFromSession();
if (newQueriesFound) {
console.log(`AI Navigator: Session now contains ${sessionQueries.length} total queries`);
}
// Note: Only processing user queries for navigation
// Assistant responses are not included in the navigation sidebar
}
/**
* Sets up a MutationObserver to watch for new chat messages.
*/
function observeChatContainer() {
if (!currentProvider) {
console.error('AI Navigator: No provider available for setting up observer');
return;
}
let chatContainer = document.body; // Fallback to body
const chatContainerSelector = currentProvider.getChatContainerSelector();
if (chatContainerSelector !== 'body') {
const specificContainer = document.querySelector(chatContainerSelector);
if (specificContainer) {
chatContainer = specificContainer;
}
}
// If no specific container found, try to find a scrollable container containing the first query
if (chatContainer === document.body) {
const selectors = currentProvider.getSelectors();
const firstQuery = document.querySelector(selectors.queries);
if (firstQuery && firstQuery.parentElement) {
// Attempt to find a more specific scrollable container
let potentialContainer = firstQuery.parentElement;
while(potentialContainer && potentialContainer !== document.body) {
if (potentialContainer.scrollHeight > potentialContainer.clientHeight) { // Check if it's scrollable
const styles = window.getComputedStyle(potentialContainer);
if (styles.overflowY === 'auto' || styles.overflowY === 'scroll') {
chatContainer = potentialContainer;
break;
}
}
potentialContainer = potentialContainer.parentElement;
}
if (chatContainer === document.body && firstQuery.parentElement.parentElement) {
// If no scrollable parent, observe the direct parent of the first query/response block
chatContainer = firstQuery.parentElement.parentElement || document.body;
}
}
}
console.log(`AI Navigator: Observing container for ${currentProvider.name}:`, chatContainer);
const observer = new MutationObserver((mutationsList, observer) => {
// Debounce the processing to avoid multiple rapid updates
clearTimeout(observerTimeout);
observerTimeout = setTimeout(() => {
console.log(`AI Navigator: DOM changes detected for ${currentProvider.name}, reprocessing chat elements.`);
processChatElements();
// Reattach focus mode listeners in case new input fields were added
reattachInputListeners();
}, OBSERVER_DEBOUNCE_TIME);
});
observer.observe(chatContainer, { childList: true, subtree: true });
console.log(`AI Navigator: MutationObserver started for ${currentProvider.name}.`);
// Add input event listeners for immediate question detection
setupInputListeners();
}
/**
* Sets up input event listeners for immediate question detection
*/
function setupInputListeners() {
if (!currentProvider) {
console.error('AI Navigator: No provider available for setting up input listeners');
return;
}
const selectors = currentProvider.getSelectors();
console.log(`AI Navigator: Setting up input listeners for ${currentProvider.name}`);
// Listen for Enter key in input fields
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
const inputField = document.querySelector(selectors.inputField);
if (inputField && (inputField.contains(e.target) || inputField === e.target)) {
console.log(`AI Navigator: Enter key detected in input field for ${currentProvider.name}`);
// Small delay to allow the message to be processed and added to DOM
setTimeout(() => {
processChatElements();
}, 200);
}
}
});
// Listen for submit button clicks
document.addEventListener('click', (e) => {
const submitButton = document.querySelector(selectors.submitButton);
if (submitButton && (submitButton.contains(e.target) || submitButton === e.target ||
e.target.closest(selectors.submitButton))) {
console.log(`AI Navigator: Submit button clicked for ${currentProvider.name}`);
// Small delay to allow the message to be processed and added to DOM
setTimeout(() => {
processChatElements();
}, 200);
}
});
// Listen for form submissions as additional fallback
document.addEventListener('submit', (e) => {
const inputContainer = document.querySelector(selectors.inputContainer);
if (inputContainer && inputContainer.contains(e.target)) {
console.log(`AI Navigator: Form submission detected for ${currentProvider.name}`);
// Small delay to allow the message to be processed and added to DOM
setTimeout(() => {
processChatElements();
}, 200);
}
});
console.log(`AI Navigator: Input listeners set up for ${currentProvider.name}`);
}
// --- Search Functions ---
/**
* Handles search input with debouncing for better UX
*/
function handleSearch() {
const searchTerm = searchInput.value.toLowerCase().trim();
// Show/hide clear button
const searchClear = navBar.querySelector('.search-clear');
if (searchClear) {
searchClear.style.display = searchTerm ? 'block' : 'none';
}
// Debounce search for better performance
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
filterNavItems(searchTerm);
}, 200);
}
/**
* Filters navigation items based on search term
* @param {string} searchTerm - The search term to filter by
*/
function filterNavItems(searchTerm) {
allNavItems.forEach(item => {
if (!searchTerm) {
// Show all items when no search term
item.style.display = 'block';
return;
}
// Search in both summary and full text
const matchesSearch =
item.dataset.summary.includes(searchTerm) ||
item.dataset.fullText.includes(searchTerm);
item.style.display = matchesSearch ? 'block' : 'none';
});
// Reset navigation index when search results change
resetNavigationIndex();
}
/**
* Clears the search input and shows all items
*/
function clearSearch() {
searchInput.value = '';
const searchClear = navBar.querySelector('.search-clear');
if (searchClear) {
searchClear.style.display = 'none';
}
filterNavItems(''); // Show all items
}
// --- Keyboard Navigation Functions ---
/**
* Handles arrow key navigation through the sidebar items
* @param {KeyboardEvent} event - The keyboard event
*/
function handleArrowNavigation(event) {
// Only handle arrow keys when sidebar is visible and has items
if (!navBar || navBar.classList.contains('collapsed') || allNavItems.length === 0) {
return;
}
// Only handle arrow keys and Enter/Escape
if (!['ArrowUp', 'ArrowDown', 'Enter', 'Escape'].includes(event.key)) {
return;
}
// Don't interfere when user is typing in search or input fields
const activeElement = document.activeElement;
if (activeElement && (
activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA' ||
activeElement.contentEditable === 'true'
)) {
// But allow Escape to clear search if in search field
if (event.key === 'Escape' && activeElement === searchInput) {
clearSearch();
clearNavigationHighlight();
event.preventDefault();
}
return;
}
// Get only visible nav items for navigation
const visibleNavItems = allNavItems.filter(item =>
item.style.display !== 'none' && item.offsetParent !== null
);
if (visibleNavItems.length === 0) {
return;
}
event.preventDefault(); // Prevent default browser behavior
switch (event.key) {
case 'ArrowDown':
keyboardNavigationActive = true;
currentNavigationIndex = (currentNavigationIndex + 1) % visibleNavItems.length;
updateNavigationHighlight(visibleNavItems);
break;
case 'ArrowUp':
keyboardNavigationActive = true;
currentNavigationIndex = currentNavigationIndex <= 0 ?
visibleNavItems.length - 1 : currentNavigationIndex - 1;
updateNavigationHighlight(visibleNavItems);
break;
case 'Enter':
if (keyboardNavigationActive && currentNavigationIndex >= 0) {
const highlightedItem = visibleNavItems[currentNavigationIndex];
if (highlightedItem) {
highlightedItem.click(); // Trigger the existing click handler
}
}
break;
case 'Escape':
clearNavigationHighlight();
break;
}
}
/**
* Updates the visual highlight for keyboard navigation
* @param {Array} visibleNavItems - Array of visible navigation items