-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
310 lines (259 loc) · 9.36 KB
/
content.js
File metadata and controls
310 lines (259 loc) · 9.36 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
// Store filtered domains with timestamps
let filteredDomainsWithTime = new Map(); // domain -> timestamp
// Function to clean domain (strip www.)
function cleanDomain(domain) {
return domain.replace(/^www\./, '');
}
// Function to check if a domain matches any filtered domain
function isDomainFiltered(domain, filteredDomains) {
const cleanedDomain = cleanDomain(domain);
return Array.from(filteredDomains).some(filtered =>
cleanDomain(filtered) === cleanedDomain
);
}
// Function to get filtered domains from search query
function getFilteredDomainsFromQuery() {
const urlParams = new URLSearchParams(window.location.search);
const query = urlParams.get('q') || '';
const domains = new Set();
// Extract all -site: domains from query
const matches = query.match(/-site:(\S+)\s*/g) || [];
matches.forEach(match => {
const domain = cleanDomain(match.replace('-site:', '').trim());
domains.add(domain);
// Add timestamp if not exists
if (!filteredDomainsWithTime.has(domain)) {
filteredDomainsWithTime.set(domain, Date.now());
}
});
// Clean up old domains
for (const [domain] of filteredDomainsWithTime) {
if (!domains.has(domain)) {
filteredDomainsWithTime.delete(domain);
}
}
return domains;
}
// Function to modify search URL with domain filters
function modifySearchWithFilters(addDomain = null, removeDomain = null) {
const urlParams = new URLSearchParams(window.location.search);
const query = urlParams.get('q') || '';
// Remove any existing -site: filters from the query
let cleanQuery = query.replace(/-site:\S+\s*/g, '').trim();
// Get current filtered domains and update as needed
const domains = getFilteredDomainsFromQuery();
if (addDomain) domains.add(cleanDomain(addDomain));
if (removeDomain) domains.delete(cleanDomain(removeDomain));
// Add -site: filter for each domain
const filters = Array.from(domains)
.map(domain => `-site:${domain}`)
.join(' ');
// Combine clean query with filters
const newQuery = cleanQuery + (filters ? ' ' + filters : '');
// Only update if the query would change
if (newQuery !== query) {
urlParams.set('q', newQuery);
const newUrl = `${window.location.pathname}?${urlParams.toString()}`;
window.location.href = newUrl;
}
}
// Create filter controls for a search result
function createFilterControls(result, domain) {
const controls = document.createElement('div');
controls.className = 'filter-controls';
// Create Pacman button
const button = document.createElement('button');
button.className = 'filter-button';
button.title = 'Filter out this domain';
const isFiltered = isDomainFiltered(domain, getFilteredDomainsFromQuery());
if (isFiltered) {
button.classList.add('active');
}
button.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
<path d="M5.636 5.636a9 9 0 0 1 13.397 .747l-5.619 5.617l5.619 5.617a9 9 0 1 1 -13.397 -11.981z" />
<circle cx="11.5" cy="7.5" r="1" fill="currentColor" />
</svg>
`;
button.addEventListener('click', () => {
const isCurrentlyFiltered = button.classList.contains('active');
if (!isCurrentlyFiltered) {
button.classList.add('active');
modifySearchWithFilters(domain);
} else {
button.classList.remove('active');
modifySearchWithFilters(null, domain);
}
});
controls.appendChild(button);
return controls;
}
// Create a single domain pill
function createDomainPill(domain) {
const pill = document.createElement('div');
pill.className = 'domain-pill';
// Filter icon
const filterIcon = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 4a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v2.586a1 1 0 0 1-.293.707l-6.414 6.414v6.586a1 1 0 0 1-1.414.914l-2-1A1 1 0 0 1 11 19.414V13.414L4.293 7.293A1 1 0 0 1 4 6.586V4z"/>
</svg>
`;
// Close icon
const closeIcon = `
<svg class="domain-pill-close" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>
`;
pill.innerHTML = `
${filterIcon}
<span>${domain}</span>
${closeIcon}
`;
// Add click handler to close button
const closeButton = pill.querySelector('.domain-pill-close');
closeButton.addEventListener('click', (e) => {
e.stopPropagation();
modifySearchWithFilters(null, domain);
});
return pill;
}
// Create show more pill
function createShowMorePill(totalCount) {
const pill = document.createElement('div');
pill.className = 'domain-pill show-more-pill';
const remainingCount = totalCount - 3;
pill.innerHTML = `
<span>Show ${remainingCount} more</span>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 15l-6-6-6 6"/>
</svg>
`;
pill.addEventListener('click', () => {
const container = document.querySelector('.filtered-domains-pills');
if (container) {
container.classList.toggle('expanded');
const remainingCount = totalCount - 3;
const text = container.classList.contains('expanded') ? 'Show less' : `Show ${remainingCount} more`;
pill.querySelector('span').textContent = text;
}
});
return pill;
}
// Create or update the filtered domains pills
function updateFilteredDomainsPills() {
let container = document.querySelector('.filtered-domains-pills');
if (!container) {
container = document.createElement('div');
container.className = 'filtered-domains-pills';
// Insert into the main search results container
const rcnt = document.querySelector('#rcnt');
if (rcnt) {
const center = rcnt.querySelector('#center_col');
if (center) {
center.insertBefore(container, center.firstChild);
} else {
rcnt.insertBefore(container, rcnt.firstChild);
}
} else {
console.log('Debug - Could not find main container (#rcnt)');
}
}
// Get and sort domains by timestamp (most recent first)
const domains = getFilteredDomainsFromQuery();
// Clear existing content
container.innerHTML = '';
if (domains.size === 0) {
const emptyMessage = document.createElement('div');
emptyMessage.className = 'filtered-domains-empty';
emptyMessage.textContent = 'No filtered domains';
container.appendChild(emptyMessage);
return;
}
// Sort domains by timestamp
const sortedDomains = Array.from(domains)
.sort((a, b) => filteredDomainsWithTime.get(b) - filteredDomainsWithTime.get(a));
// Add first 3 most recent pills
const visibleDomains = sortedDomains.slice(0, 3);
visibleDomains.forEach(domain => {
const pill = createDomainPill(domain);
container.appendChild(pill);
});
// Add show more pill if needed
if (domains.size > 3) {
const showMorePill = createShowMorePill(domains.size);
container.appendChild(showMorePill);
// Add remaining pills (hidden initially)
const remainingDomains = sortedDomains.slice(3);
const hiddenContainer = document.createElement('div');
hiddenContainer.className = 'hidden-pills';
remainingDomains.forEach(domain => {
const pill = createDomainPill(domain);
hiddenContainer.appendChild(pill);
});
container.appendChild(hiddenContainer);
}
}
// Process search results
function updateResults() {
const searchResults = document.querySelectorAll('div.g');
searchResults.forEach(result => {
const link = result.querySelector('a');
if (!link) return;
try {
const domain = new URL(link.href).hostname;
// Add filter controls if not already present
if (!result.querySelector('.filter-controls')) {
const controls = createFilterControls(result, domain);
result.insertBefore(controls, result.firstChild);
}
} catch (e) {
console.error('Error processing URL:', e);
}
});
// Update pills
updateFilteredDomainsPills();
}
// Create observer to handle dynamic loading of results
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length) {
updateResults();
}
});
});
// Function to initialize the extension
function initialize() {
console.log('Debug - Initializing extension');
// Try multiple times in case the page is still loading
let attempts = 0;
const maxAttempts = 5;
function tryInitialize() {
const searchResultsContainer = document.getElementById('search');
console.log('Debug - Search container found:', !!searchResultsContainer);
if (searchResultsContainer) {
observer.observe(searchResultsContainer, {
childList: true,
subtree: true
});
// Initial update
updateResults();
updateFilteredDomainsPills();
} else if (attempts < maxAttempts) {
attempts++;
setTimeout(tryInitialize, 500);
}
}
tryInitialize();
}
// Start observing and handle dynamic page updates
initialize();
// Re-initialize on URL changes (for single-page navigation)
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
initialize();
}
}).observe(document, { subtree: true, childList: true });