-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
310 lines (276 loc) · 11.1 KB
/
Copy pathsearch.js
File metadata and controls
310 lines (276 loc) · 11.1 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
// Search logic
import { userTracker } from './tracking.js';
export function setupSearch() {
const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');
const suggestionsBox = document.getElementById('search-suggestions');
// Create ghost text element for autocomplete (commands/props only)
const ghostInput = document.createElement('span');
ghostInput.id = 'search-ghost';
ghostInput.style.position = 'absolute';
ghostInput.style.pointerEvents = 'none';
ghostInput.style.color = '#bdbdbd';
ghostInput.style.opacity = '0.7';
ghostInput.style.fontSize = 'inherit';
ghostInput.style.fontFamily = 'inherit';
ghostInput.style.left = (searchInput.offsetLeft) + 'px';
ghostInput.style.top = (searchInput.offsetHeight) + 'px';
ghostInput.style.width = searchInput.offsetWidth + 'px';
ghostInput.style.height = 'auto';
ghostInput.style.lineHeight = 'normal';
ghostInput.style.whiteSpace = 'pre';
ghostInput.style.zIndex = '10';
ghostInput.style.userSelect = 'none';
ghostInput.style.paddingLeft = window.getComputedStyle(searchInput).paddingLeft;
// Insert ghost below input
searchInput.parentNode.insertBefore(ghostInput, searchInput.nextSibling);
let ghostSuggestion = '';
let lastQuery = '';
let abortController = null;
searchInput.addEventListener('input', function() {
const query = this.value;
if (!query) {
suggestionsBox.style.display = 'none';
ghostInput.textContent = '';
ghostSuggestion = '';
return;
}
lastQuery = query;
// Command and prop completions
const commands = ['/g', '/b', '/ddg', '/yt', '/gh'];
const props = ['images', 'videos'];
let completion = '';
let found = false;
// Command completion
for (const cmd of commands) {
if (cmd.startsWith(query) && cmd !== query) {
completion = cmd.slice(query.length);
ghostSuggestion = cmd;
found = true;
break;
}
}
// Prop completion (after space)
if (!found && query.includes(' ')) {
const parts = query.split(' ');
const last = parts[parts.length - 1];
for (const prop of props) {
if (prop.startsWith(last) && prop !== last) {
completion = prop.slice(last.length);
ghostSuggestion = parts.slice(0, -1).join(' ') + ' ' + prop;
found = true;
break;
}
}
}
if (found) {
ghostInput.textContent = query + completion;
} else {
ghostInput.textContent = '';
ghostSuggestion = '';
}
// Combine user history with DDG suggestions
showSearchSuggestions(query);
});
// Tab to autocomplete ghost suggestion
searchInput.addEventListener('keydown', function(e) {
if (e.key === 'Tab' && ghostSuggestion) {
e.preventDefault();
searchInput.value = ghostSuggestion;
ghostInput.textContent = '';
ghostSuggestion = '';
searchInput.dispatchEvent(new Event('input'));
}
});
// Handle click on suggestion
suggestionsBox.addEventListener('mousedown', function(e) {
if (e.target.classList.contains('suggestion-item')) {
let suggestionText = e.target.textContent;
// Remove the clock emoji from history suggestions
if (e.target.classList.contains('history-suggestion')) {
suggestionText = suggestionText.replace('🕒 ', '');
}
searchInput.value = suggestionText;
suggestionsBox.style.display = 'none';
// Optionally, submit the form here
// searchForm.dispatchEvent(new Event('submit'));
}
});
// Hide suggestions on blur
searchInput.addEventListener('blur', function() {
setTimeout(() => suggestionsBox.style.display = 'none', 100);
});
// Function to show combined search suggestions
function showSearchSuggestions(query) {
if (query.length < 2) {
suggestionsBox.style.display = 'none';
return;
}
// Get user's search history suggestions only if tracking is enabled
const trackingEnabled = localStorage.getItem('dashboard-tracking') !== 'false';
const historySuggestions = trackingEnabled ? userTracker.getSearchSuggestions(query, 3) : [];
// Get DDG suggestions
if (abortController) abortController.abort();
abortController = new AbortController();
fetch(`https://duckduckgo.com/ac/?q=${encodeURIComponent(query.trim())}`, { signal: abortController.signal })
.then(res => res.json())
.then(data => {
if (searchInput.value.trim() !== lastQuery.trim()) return;
let suggestions = [];
// Add history suggestions first (marked with a different style)
if (historySuggestions.length > 0) {
suggestions = historySuggestions.map(suggestion =>
`<div class="suggestion-item history-suggestion" title="From your search history">🕒 ${suggestion}</div>`
);
}
// Add DDG suggestions
if (Array.isArray(data) && data.length > 0) {
const ddgSuggestions = data.slice(0, 5).map(item =>
`<div class="suggestion-item">${item.phrase}</div>`
);
suggestions = suggestions.concat(ddgSuggestions);
}
if (suggestions.length > 0) {
suggestionsBox.innerHTML = suggestions.join('');
suggestionsBox.style.display = 'block';
} else {
suggestionsBox.style.display = 'none';
}
})
.catch(() => {
// Fallback to just history suggestions
if (historySuggestions.length > 0) {
const suggestions = historySuggestions.map(suggestion =>
`<div class="suggestion-item history-suggestion" title="From your search history">🕒 ${suggestion}</div>`
);
suggestionsBox.innerHTML = suggestions.join('');
suggestionsBox.style.display = 'block';
} else {
suggestionsBox.style.display = 'none';
}
});
}
searchForm.addEventListener('submit', function(e) {
e.preventDefault();
let raw = searchInput.value.trim();
if (!raw) return;
// Command parsing
// Syntax: /g images cats, /u youtube.com
// Providers: /g (Google), /b (Bing), /ddg (DuckDuckGo), /yt (YouTube), /gh (GitHub), /u (URL)
// Filters: images, videos
let engine = document.querySelector('.custom-dropdown[data-name="search-engine"] input[type="hidden"]').value;
let filter = document.querySelector('.custom-dropdown[data-name="search-filter"] input[type="hidden"]').value;
let query = raw;
const providerMap = {
'/g': 'google',
'/b': 'bing',
'/ddg': 'duckduckgo',
'/yt': 'youtube',
'/gh': 'github',
'/u': 'url'
};
const filterMap = {
'images': 'images',
'videos': 'videos'
};
// Detect provider command
const providerMatch = raw.match(/^\/(g|b|ddg|yt|gh|u)\b/i);
if (providerMatch) {
engine = providerMap[providerMatch[0].toLowerCase()];
query = query.replace(providerMatch[0], '').trim();
}
// If no command is used and input looks like a URL, open it directly
if (!providerMatch) {
// Check if raw is a valid domain (e.g., youtube.com, www.youtube.com, google.com)
const urlPattern = /^(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:\/[\w\-\.~:\/?#\[\]@!$&'()*+,;=]*)?$/;
if (urlPattern.test(raw)) {
let siteUrl = raw.match(/^https?:\/\//) ? raw : `https://${raw}`;
window.open(siteUrl, '_blank');
// Track both the search and the website visit if tracking is enabled
const trackingEnabled = localStorage.getItem('dashboard-tracking') !== 'false';
if (trackingEnabled) {
userTracker.trackSearch(raw, 'url');
// Also track as a website visit
const siteName = raw.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0];
userTracker.trackWebsiteVisit(siteUrl, siteName, `https://www.google.com/s2/favicons?domain=${siteName}&sz=32`);
}
searchInput.value = '';
suggestionsBox.style.display = 'none';
return;
}
}
// Detect filter command (not for /u)
if (engine !== 'url') {
const filterMatch = query.match(/\b(images|videos)\b/i);
if (filterMatch) {
filter = filterMap[filterMatch[0].toLowerCase()];
query = query.replace(filterMatch[0], '').trim();
}
}
let url = '';
if (engine === 'url') {
// Direct URL search: open the site, optionally with search if query is present
let site = query.split(' ')[0];
let siteUrl = site.match(/^https?:\/\//) ? site : `https://${site}`;
let searchQuery = query.slice(site.length).trim();
if (searchQuery) {
// Try to append search query for common sites
if (/youtube\.com/i.test(site)) {
url = `${siteUrl}/results?search_query=${encodeURIComponent(searchQuery)}`;
} else if (/github\.com/i.test(site)) {
url = `${siteUrl}/search?q=${encodeURIComponent(searchQuery)}`;
} else if (/duckduckgo\.com/i.test(site)) {
url = `${siteUrl}/?q=${encodeURIComponent(searchQuery)}`;
} else if (/google\.com/i.test(site)) {
url = `${siteUrl}/search?q=${encodeURIComponent(searchQuery)}`;
} else if (/bing\.com/i.test(site)) {
url = `${siteUrl}/search?q=${encodeURIComponent(searchQuery)}`;
} else {
url = siteUrl;
}
} else {
url = siteUrl;
}
// Track website visit for /u command
const trackingEnabled = localStorage.getItem('dashboard-tracking') !== 'false';
if (trackingEnabled) {
const siteName = site.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0];
userTracker.trackWebsiteVisit(url, siteName, `https://www.google.com/s2/favicons?domain=${siteName}&sz=32`);
}
} else {
switch (engine) {
case 'google':
url = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
if (filter === 'images') url += '&tbm=isch';
if (filter === 'videos') url += '&tbm=vid';
break;
case 'bing':
url = `https://www.bing.com/search?q=${encodeURIComponent(query)}`;
if (filter === 'images') url += '&scope=images';
if (filter === 'videos') url += '&scope=video';
break;
case 'duckduckgo':
url = `https://duckduckgo.com/?q=${encodeURIComponent(query)}`;
if (filter === 'images') url += '&iax=images&ia=images';
if (filter === 'videos') url += '&iax=videos&ia=videos';
break;
case 'youtube':
url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`;
break;
case 'github':
url = `https://github.com/search?q=${encodeURIComponent(query)}`;
break;
default:
url = `https://www.google.com/search?q=${encodeURIComponent(query)}`;
}
}
window.open(url, '_blank');
// Track the search if tracking is enabled
const trackingEnabled = localStorage.getItem('dashboard-tracking') !== 'false';
if (trackingEnabled) {
userTracker.trackSearch(raw, engine);
}
searchInput.value = '';
suggestionsBox.style.display = 'none';
});
}