-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
355 lines (307 loc) · 10.4 KB
/
index.js
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
// DOM Elements
const loadingBar = document.getElementById('loading-bar');
const searchInput = document.getElementById('search-input');
const cursor = document.getElementById('cursor');
const searchContainer = document.getElementById('search-container');
const shortcutContainer = document.getElementById('shortcut-container');
const addShortcutButton = document.getElementById('add-shortcut');
const settingsButton = document.getElementById('settings-button');
const settingsModal = document.getElementById('settings-modal');
const searchEngineButtons = document.getElementById('search-engine-buttons');
const newTabToggle = document.getElementById('new-tab-toggle');
const gradientToggle = document.getElementById('gradient-toggle');
// Load shortcuts from localStorage
let shortcuts = JSON.parse(localStorage.getItem('shortcuts')) || [];
// Settings and state management
const settings = {
// Set DuckDuckGo as the default search engine if none is saved
searchEngine: localStorage.getItem('searchEngine') || 'duckduckgo',
openInNewTab: localStorage.getItem('openInNewTab') === 'true' || false,
gradientBackground: localStorage.getItem('gradientBackground') !== 'false',
};
// Search engine URLs (only Google and DuckDuckGo)
const searchEngines = {
google: 'https://www.google.com/search?q=',
duckduckgo: 'https://duckduckgo.com/?q='
};
// Initialize Search Engine Buttons UI
const engineButtons = searchEngineButtons.querySelectorAll('.search-engine-button');
function updateActiveEngine() {
engineButtons.forEach(button => {
if (button.getAttribute('data-engine') === settings.searchEngine) {
button.classList.add('active');
} else {
button.classList.remove('active');
}
});
}
engineButtons.forEach(button => {
button.addEventListener('click', () => {
settings.searchEngine = button.getAttribute('data-engine');
localStorage.setItem('searchEngine', settings.searchEngine);
updateActiveEngine();
});
});
updateActiveEngine();
/* Loading Bar Functions */
function startLoading() {
loadingBar.classList.add('loading');
}
function stopLoading() {
loadingBar.classList.remove('loading');
// Reset the width after animation completes
setTimeout(() => {
loadingBar.style.width = '0';
}, 200);
}
/* Navigation Function with Loading Bar */
function navigateWithLoading(url, newTab = false) {
startLoading();
if (newTab) {
window.open(url, '_blank');
stopLoading(); // Stop loading immediately for new tabs
} else {
// Add a small delay to show the loading animation
setTimeout(() => {
window.location.href = url;
}, 500);
}
}
/* Update Cursor Position */
function updateCursorPosition() {
const containerRect = searchContainer.getBoundingClientRect();
const cursorX = containerRect.width / 2;
const cursorY = containerRect.height / 2;
cursor.style.left = `${cursorX}px`;
cursor.style.top = `${cursorY}px`;
cursor.style.transform = 'translate(-50%, -50%)';
}
/* URL Validation */
function isValidURL(string) {
const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
if (domainRegex.test(string)) {
return true;
}
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
/* Handle Search Input using Loading Bar */
function handleInput() {
let input = searchInput.value.trim();
if (isValidURL(input)) {
if (!input.startsWith('http://') && !input.startsWith('https://')) {
input = 'https://' + input;
}
navigateWithLoading(input, settings.openInNewTab);
} else {
const query = encodeURIComponent(input);
const searchUrl = searchEngines[settings.searchEngine] + query;
navigateWithLoading(searchUrl, settings.openInNewTab);
}
searchInput.value = '';
cursor.style.display = 'inline';
}
/* Get Domain from URL */
function getDomainFromURL(url) {
try {
const domain = new URL(url).hostname;
return domain.replace(/^www\./, '');
} catch {
return null;
}
}
/* Get Favicon URL */
function getFavicon(url) {
return `https://wilful-amethyst-butterfly.faviconkit.com/${url}/48`;
}
/* Handle Shortcut Click with Loading Bar */
function handleShortcutClick(url) {
navigateWithLoading(url, settings.openInNewTab);
}
/* Render Shortcuts */
async function renderShortcuts() {
shortcutContainer.innerHTML = '';
for (const [index, shortcut] of shortcuts.entries()) {
const shortcutElement = document.createElement('div');
shortcutElement.className = 'shortcut';
// Create menu button
const menuElement = document.createElement('div');
menuElement.className = 'shortcut-menu';
menuElement.innerHTML = '⋮';
// Create icon element with favicon background
const iconElement = document.createElement('div');
iconElement.className = 'shortcut-icon';
const domain = getDomainFromURL(shortcut.url);
const faviconUrl = getFavicon(domain);
iconElement.style.backgroundImage = `url(${faviconUrl})`;
// Create name element
const nameElement = document.createElement('div');
nameElement.className = 'shortcut-name';
nameElement.textContent = shortcut.name;
// Toggle menu options
menuElement.onclick = (e) => {
e.stopPropagation();
const menuOptions = menuElement.nextElementSibling;
const isActive = menuElement.classList.contains('active');
// Close other active menus
document.querySelectorAll('.shortcut-menu.active').forEach(menu => {
menu.classList.remove('active');
menu.nextElementSibling.style.display = 'none';
});
if (!isActive) {
menuElement.classList.add('active');
menuOptions.style.display = 'block';
} else {
menuElement.classList.remove('active');
menuOptions.style.display = 'none';
}
};
// Create menu options container
const menuOptions = document.createElement('div');
menuOptions.className = 'menu-options';
// Edit option
const editOption = document.createElement('div');
editOption.textContent = 'Edit';
editOption.onclick = (e) => {
e.stopPropagation();
editShortcut(index);
};
// Remove option
const removeOption = document.createElement('div');
removeOption.textContent = 'Remove';
removeOption.onclick = (e) => {
e.stopPropagation();
removeShortcut(index);
};
menuOptions.appendChild(editOption);
menuOptions.appendChild(removeOption);
// Append children to shortcut element
shortcutElement.appendChild(menuElement);
shortcutElement.appendChild(menuOptions);
shortcutElement.appendChild(iconElement);
shortcutElement.appendChild(nameElement);
// Use loading bar navigation when clicking shortcut
shortcutElement.onclick = () => {
handleShortcutClick(shortcut.url);
};
shortcutContainer.appendChild(shortcutElement);
}
}
/* Shortcut Management Functions */
function addShortcut() {
const name = prompt('Enter shortcut name:');
let url = prompt('Enter shortcut URL:');
if (name && url) {
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
shortcuts.push({ name, url });
saveShortcuts();
renderShortcuts();
}
}
function editShortcut(index) {
const shortcut = shortcuts[index];
const name = prompt('Edit shortcut name:', shortcut.name);
let url = prompt('Edit shortcut URL:', shortcut.url);
if (name && url) {
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
shortcuts[index] = { name, url };
saveShortcuts();
renderShortcuts();
}
}
function removeShortcut(index) {
shortcuts.splice(index, 1);
saveShortcuts();
renderShortcuts();
}
function saveShortcuts() {
localStorage.setItem('shortcuts', JSON.stringify(shortcuts));
}
/* Background Gradient Functions */
// Now generates two random colors for the gradient
function setRandomGradient() {
if (settings.gradientBackground) {
const colors = [
generateRandomColor(),
generateRandomColor()
];
document.body.style.background = `linear-gradient(45deg, ${colors.join(', ')})`;
} else {
document.body.style.background = '#2a2828';
}
}
function generateRandomColor() {
const hue = Math.floor(Math.random() * 360);
return `hsla(${hue}, 70%, 45%, 0.8)`;
}
/* Settings Modal Handlers */
settingsButton.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent the document click handler from immediately closing it
settingsModal.style.visibility = 'visible';
// Use setTimeout to ensure the visibility change happens before the transform
setTimeout(() => {
settingsModal.classList.toggle('show');
}, 0);
});
document.addEventListener('click', (e) => {
if (!settingsModal.contains(e.target) && e.target !== settingsButton) {
settingsModal.classList.remove('show');
// Wait for the transition to complete before hiding
setTimeout(() => {
settingsModal.style.visibility = 'hidden';
}, 300); // Match this with your transition duration
}
});
/* Settings Options Handlers */
newTabToggle.addEventListener('change', (e) => {
settings.openInNewTab = e.target.checked;
localStorage.setItem('openInNewTab', settings.openInNewTab);
});
gradientToggle.addEventListener('change', (e) => {
settings.gradientBackground = e.target.checked;
localStorage.setItem('gradientBackground', settings.gradientBackground);
setRandomGradient();
});
/* General Event Listeners */
searchInput.addEventListener('input', () => {
cursor.style.display = searchInput.value ? 'none' : 'inline';
});
searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleInput();
}
});
window.addEventListener('resize', updateCursorPosition);
addShortcutButton.onclick = addShortcut;
/* Initialization on Page Load */
window.addEventListener('load', () => {
searchInput.focus();
setRandomGradient();
updateCursorPosition();
renderShortcuts();
});
/* Hide Shortcut Menus When Clicking Outside */
function hideMenus(event) {
if (!event.target.closest('.shortcut')) {
document.querySelectorAll('.shortcut-menu.active').forEach(menu => {
menu.classList.remove('active');
menu.nextElementSibling.style.display = 'none';
});
}
}
document.addEventListener('click', hideMenus);
/* Focus on the Search Input When Clicking Anywhere on the Page */
function focusSearchInput(event) {
if (event.target !== searchInput && !searchInput.contains(event.target)) {
searchInput.focus();
}
}
document.addEventListener('click', focusSearchInput);