-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathsearch.js
More file actions
451 lines (367 loc) · 16.6 KB
/
search.js
File metadata and controls
451 lines (367 loc) · 16.6 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
/*
* Material You NewTab
* Copyright (c) 2023-2025 XengShi
* Licensed under the GNU General Public License v3.0 (GPL-3.0)
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
*/
const searchbar = document.getElementById("searchbar");
const searchInput = document.getElementById("searchQ");
const languageCode = (localStorage.getItem("selectedLanguage") || "en").slice(0, 2);
const searchQueryURLs = {
engine1: "https://www.google.com/search?q=",
engine2: "https://duckduckgo.com/?q=",
engine3: "https://bing.com/?q=",
engine4: "https://search.brave.com/search?q=",
engine5: "https://www.youtube.com/results?search_query=",
engine6: "https://www.google.com/search?tbm=isch&q=",
engine7: "https://www.reddit.com/search/?q=",
engine8: `https://${languageCode}.wikipedia.org/wiki/Special:Search?search=`,
engine9: "https://www.quora.com/search?q="
};
// Showing border or outline when you click on the searchbar
searchbar.addEventListener("click", function (event) {
event.stopPropagation();
searchbar.classList.add("active");
if (!event.target.closest(".dropdown-btn")) {
searchInput.focus();
}
});
document.addEventListener("click", function (event) {
// Check if the clicked element is not the searchbar
if (!searchbar.contains(event.target)) {
searchbar.classList.remove("active");
}
});
// Search mode function
const searchWith = document.getElementById("searchWithHint");
const searchEngines = document.querySelectorAll(".searchEnginesContainer .search-engine");
const searchEnginesContainer = document.querySelector(".searchEnginesContainer");
let activeSearchMode = localStorage.getItem("activeSearchMode") || "search-with";
searchWith.addEventListener("click", function (event) {
activeSearchMode = (activeSearchMode === "search-with") ? "search-on" : "search-with";
searchEnginesContainer.classList.toggle("show");
toggleSearchEngines(activeSearchMode);
event.stopPropagation();
searchInput.focus();
searchbar.classList.add("active");
setTimeout(() => {
searchEnginesContainer.classList.remove("show");
}, 300);
});
function toggleSearchEngines(category) {
const defaultItems = {
"search-with": "engine0",
"search-on": "engine5",
};
const checkeditem = localStorage.getItem(`selectedSearchEngine-${category}`) || defaultItems[category];
const searchModeName = category === "search-with" ? "searchWithHint" : "searchOnHint";
searchWith.innerText = translations[currentLanguage][searchModeName] || translations["en"][searchModeName];
searchEngines.forEach(engine => {
if (engine.getAttribute("data-category") === category) {
engine.style.display = "flex";
} else {
engine.style.display = "none";
}
if (engine.lastElementChild.value === checkeditem) {
const radioBtn = engine.querySelector('input[type="radio"]');
radioBtn.checked = true;
radioBtn.dispatchEvent(new Event("change"));
}
});
}
// Search function
const dropdown = document.querySelector(".dropdown-content");
dropdown.addEventListener("click", (event) => {
if (dropdown.classList.contains("show")) {
event.stopPropagation();
dropdown.classList.remove("show");
searchInput.focus();
}
});
document.addEventListener("click", (event) => {
if (dropdown.classList.contains("show")) {
event.stopPropagation();
dropdown.classList.remove("show");
}
});
document.querySelector(".dropdown-btn").addEventListener("click", function () {
const resultBox = document.getElementById("resultBox");
if (resultBox.classList.toString().includes("show")) return;
// Clear selected state and reset index when dropdown opens
dropdownItems.forEach(item => item.classList.remove("selected"));
selectedIndex = -1;
dropdown.classList.toggle("show");
});
const enterBTN = document.getElementById("enterBtn");
const searchEngineRadio = document.getElementsByName("search-engine");
const searchDropdowns = document.querySelectorAll('[id$="-dropdown"]:not(*[data-default])');
const defaultEngine = document.querySelector('#default-dropdown-item div[id$="-dropdown"]');
const sortDropdown = () => {
// Change the elements to the array
const elements = Array.from(searchDropdowns);
// Sort the dropdown
const sortedDropdowns = elements.sort((a, b) => {
const engineA = parseInt(a.getAttribute("data-engine"), 10);
const engineB = parseInt(b.getAttribute("data-engine"), 10);
return engineA - engineB;
})
// get the parent
const parent = sortedDropdowns[0]?.parentNode;
// Append the items if parent exists.
if (parent) {
sortedDropdowns.forEach(item => parent.appendChild(item));
}
}
// This will add event listener for click in the search bar
searchDropdowns.forEach(element => {
element.addEventListener("click", () => {
const engine = element.getAttribute("data-engine");
const radioButton = document.querySelector(`input[type="radio"][value="engine${engine}"]`);
const selector = `*[data-engine-name=${element.getAttribute("data-engine-name")}]`;
radioButton.checked = true;
// Swap the dropdown and sort them
swapDropdown(selector);
sortDropdown()
localStorage.setItem(`selectedSearchEngine-${radioButton.parentElement.dataset.category}`, radioButton.value);
localStorage.setItem(`activeSearchMode`, radioButton.parentElement.dataset.category);
});
});
// Make entire search-engine div clickable
document.querySelectorAll(".search-engine").forEach((engineDiv) => {
engineDiv.addEventListener("click", (event) => {
event.stopPropagation();
const radioButton = engineDiv.querySelector('input[type="radio"]');
radioButton.checked = true;
const radioButtonValue = radioButton.value.charAt(radioButton.value.length - 1);
const selector = `[data-engine="${radioButtonValue}"]`;
// Swap the dropdown
swapDropdown(selector);
sortDropdown();
localStorage.setItem(`selectedSearchEngine-${radioButton.parentElement.dataset.category}`, radioButton.value);
localStorage.setItem(`activeSearchMode`, radioButton.parentElement.dataset.category);
searchInput.focus();
searchbar.classList.add("active");
});
});
/**
* Swap attributes and contents between the default engine and a selected element.
* @param {HTMLElement} defaultEngine - The current default engine element.
* @param {HTMLElement} selectedElement - The clicked or selected element.
*/
function swapDropdown(selectedElement) {
// Swap innerHTML
const element = document.querySelector(selectedElement);
const tempHTML = defaultEngine.innerHTML;
defaultEngine.innerHTML = element.innerHTML;
element.innerHTML = tempHTML;
// Swap attributes
["data-engine", "data-engine-name", "id"].forEach(attr => {
const tempAttr = defaultEngine.getAttribute(attr);
defaultEngine.setAttribute(attr, element.getAttribute(attr));
element.setAttribute(attr, tempAttr);
});
}
// Function to perform search
function performSearch(query) {
const selectedOption = document.querySelector('input[name="search-engine"]:checked').value;
const searchTerm = query || searchInput.value;
if (searchTerm !== "") {
if (selectedOption === "engine0") {
try {
if (isFirefox) {
browser.search.query({ text: searchTerm });
} else {
chrome.search.query({ text: searchTerm });
}
} catch (error) {
// Fallback to Google if an error occurs
var fallbackUrl = searchQueryURLs.engine1 + encodeURIComponent(searchTerm);
window.location.href = fallbackUrl;
}
} else {
var searchUrl = searchQueryURLs[selectedOption] + encodeURIComponent(searchTerm);
window.location.href = searchUrl;
}
}
}
// Event listeners
enterBTN.addEventListener("click", () => performSearch());
// Enter key handling is managed in the search suggestions keydown listener
// Set selected search engine from local storage
const storedSearchEngine = localStorage.getItem(`selectedSearchEngine-${activeSearchMode}`);
toggleSearchEngines(activeSearchMode);
if (storedSearchEngine) {
// Find Serial Number - SN with the help of charAt.
const storedSearchEngineSN = storedSearchEngine.charAt(storedSearchEngine.length - 1);
const defaultDropdownSN = document.querySelector("*[data-default]").getAttribute("data-engine");
// check if the default selected search engine is same as the stored one.
if (storedSearchEngineSN !== defaultDropdownSN) {
// The following line will find out the appropriate dropdown for the selected search engine.
const selector = `*[data-engine="${storedSearchEngineSN}"]`;
swapDropdown(selector);
sortDropdown();
}
const selectedRadioButton = document.querySelector(`input[name="search-engine"][value="${storedSearchEngine}"]`);
if (selectedRadioButton) {
selectedRadioButton.checked = true;
}
}
const dropdownItems = document.querySelectorAll(".dropdown-item:not(*[data-default])");
let selectedIndex = -1;
// Function to update the selected item
function updateSelection() {
// let hasSelected = [];
dropdownItems.forEach((item, index) => {
item.addEventListener("mouseenter", () => {
item.classList.add("selected");
})
item.addEventListener("mouseleave", () => {
item.classList.remove("selected");
})
if (index === selectedIndex) {
item.focus()
item.classList.add("selected");
} else {
item.focus()
item.classList.remove("selected");
}
});
}
// Event listener for keydown events to navigate up/down
document.querySelector(".dropdown").addEventListener("keydown", function (event) {
if (dropdown.classList.contains("show")) {
if (event.key === "ArrowDown") {
event.preventDefault(); // Prevent the page from scrolling
selectedIndex = (selectedIndex + 1) % dropdownItems.length; // Move down, loop around
// Scroll the newly selected item into view
const activeElement = dropdownItems[selectedIndex];
activeElement.scrollIntoView({ behavior: "smooth", block: "nearest" });
} else if (event.key === "ArrowUp") {
event.preventDefault(); // Prevent the page from scrolling
selectedIndex = (selectedIndex - 1 + dropdownItems.length) % dropdownItems.length; // Move up, loop around
// Scroll the newly selected item into view
const activeElement = dropdownItems[selectedIndex];
activeElement.scrollIntoView({ behavior: "smooth", block: "nearest" });
} else if (event.key === "Enter") {
const selectedItem = document.querySelector(".dropdown-content .selected");
if (!selectedItem) return;
const engine = selectedItem.getAttribute("data-engine");
const radioButton = document.querySelector(`input[type="radio"][value="engine${engine}"]`);
radioButton.checked = true;
// Swap the dropdown and sort them
swapDropdown(`*[data-engine="${engine}"]`);
sortDropdown();
localStorage.setItem("selectedSearchEngine", radioButton.value);
// Close the dropdown after selection
dropdown.classList.remove("show");
searchInput.focus();
}
updateSelection();
}
});
// Initial setup for highlighting
updateSelection();
// Event listener for search engine radio buttons
searchEngineRadio.forEach((radio) => {
radio.addEventListener("change", () => {
const selectedOption = document.querySelector('input[name="search-engine"]:checked');
localStorage.setItem(`selectedSearchEngine-${selectedOption.parentElement.dataset.category}`, selectedOption.value);
localStorage.setItem(`activeSearchMode`, selectedOption.parentElement.dataset.category);
});
});
/* ------ Event Listeners for Searchbar dropdown ------ */
const searchIconContainer = document.querySelectorAll(".searchIcon");
const showEngineContainer = () => {
searchIconContainer[1].style.display = "none";
searchIconContainer[0].style.display = "block";
document.getElementById("search-with-container").style.visibility = "visible";
}
const hideEngineContainer = () => {
searchIconContainer[0].style.display = "none";
searchIconContainer[1].style.display = "block";
document.getElementById("search-with-container").style.visibility = "hidden";
}
const initShortCutSwitch = (element) => {
if (element.checked) {
hideEngineContainer();
localStorage.setItem("showShortcutSwitch", true)
} else {
showEngineContainer();
localStorage.setItem("showShortcutSwitch", false)
}
}
// Hiding Search Icon And Search With Options for Search switch shortcut
const hideSearchWith = document.getElementById("shortcut_switchcheckbox");
hideSearchWith.addEventListener("change", (e) => {
initShortCutSwitch(e.target);
// Fetch active search mode from storage
let activeSearchMode = localStorage.getItem("activeSearchMode") || "search-with";
toggleSearchEngines(activeSearchMode);
// Get the selected search engine from localStorage
const storedSearchEngine = localStorage.getItem(`selectedSearchEngine-${activeSearchMode}`);
// Find the corresponding radio button
const selectedRadioButton = document.querySelector(`input[name="search-engine"][value="${storedSearchEngine}"]`);
selectedRadioButton.checked = true;
// Ensure UI is updated properly
const storedSearchEngineSN = storedSearchEngine.charAt(storedSearchEngine.length - 1);
const selector = `*[data-engine="${storedSearchEngineSN}"]`;
swapDropdown(selector);
sortDropdown();
});
// Hiding search bar and search engine container based on saved preference
function handleSearchVisibility(isChecked) {
const searchBar = document.getElementById("searchbar");
const searchWithContainer = document.getElementById("search-with-container");
// show/hide search bar
searchBar.style.display = isChecked ? "none" : "block";
// also take "showShortcutSwitch" into account while showing/hiding search with container
const isShortCutSwitchEnabled = localStorage.getItem("showShortcutSwitch").toString() === "true";
searchWithContainer.style.display = (isChecked || isShortCutSwitchEnabled) ? "none" : "flex"
// disable the shortcut switch if search is hidden
const shortcutSwitchParent = document.getElementById("hideSearchWith")?.parentElement?.parentElement
if(isChecked) shortcutSwitchParent.classList.add("inactive");
else shortcutSwitchParent.classList.remove("inactive");
}
const hideSearchCheckbox = document.getElementById("hideSearchCheckbox")
hideSearchCheckbox.addEventListener("change", (e) => {
const isChecked = e.target.checked;
handleSearchVisibility(isChecked);
// update localStorage
localStorage.setItem("hideSearch", isChecked);
})
// Initialize search visibility based on saved preference
if (localStorage.getItem("hideSearch")) {
const isSearchHidden = localStorage.getItem("hideSearch").toString() === "true";
hideSearchCheckbox.checked = isSearchHidden;
handleSearchVisibility(isSearchHidden);
}
// Intialize shortcut switch
if (localStorage.getItem("showShortcutSwitch")) {
const isShortCutSwitchEnabled = localStorage.getItem("showShortcutSwitch").toString() === "true";
document.getElementById("shortcut_switchcheckbox").checked = isShortCutSwitchEnabled;
if (isShortCutSwitchEnabled) {
hideEngineContainer();
} else if (!isShortCutSwitchEnabled) {
showEngineContainer()
}
} else {
localStorage.setItem("showShortcutSwitch", false);
}
initShortCutSwitch(hideSearchWith);
document.addEventListener("keydown", function (event) {
// Prevent shortcut if modal, menu, or bookmarks sidebar is open
const modalContainer = document.getElementById("prompt-modal-container");
if (
modalContainer?.style.display === "flex" ||
menuBar.style.display !== "none" ||
bookmarkSidebar.classList.contains("open")
) {
return;
}
if (event.key === "/" && event.target.tagName !== "INPUT" && event.target.tagName !== "TEXTAREA" && event.target.isContentEditable !== true) {
event.preventDefault();
searchInput.focus();
searchbar.classList.add("active");
}
});