-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.js
More file actions
554 lines (479 loc) · 22.4 KB
/
main.js
File metadata and controls
554 lines (479 loc) · 22.4 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
import { renderCalendar } from './widgets/calendar.js';
import { renderTodo } from './widgets/todo.js';
function updateClock() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const mins = String(now.getMinutes()).padStart(2, '0');
document.getElementById('clock').textContent = `${hours}:${mins}`;
}
const weatherCodes = {
0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45: "Fog", 48: "Depositing rime fog", 51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow",
80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers",
95: "Thunderstorm", 96: "Thunderstorm w/ hail", 99: "Severe thunderstorm"
};
function fetchWeatherAndCity(lat, lon, tempUnit = 'celsius') {
const now = new Date();
const cachedWeather = localStorage.getItem('weatherData');
if (cachedWeather) {
const weatherData = JSON.parse(cachedWeather);
if ((now - new Date(weatherData.timestamp)) < 30 * 60 * 1000) {
document.getElementById('weather').textContent = weatherData.text;
return;
}
}
const tempUnitParam = tempUnit === 'fahrenheit' ? '&temperature_unit=fahrenheit' : '';
fetch(`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t_weather=true${tempUnitParam}`)
.then(res => res.json())
.then(data => {
const temp = Math.round(data.current_weather.temperature);
const code = data.current_weather.weathercode;
const desc = weatherCodes[code] || `Code ${code}`;
let weatherText = `${desc}, ${temp}°${tempUnit === 'celsius' ? 'C' : 'F'}`;
fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}`)
.then(res => res.json())
.then(location => {
const city = location.address.city || location.address.town || location.address.village || location.address.county || "your area";
const weatherString = `${city}: ${weatherText}`;
document.getElementById('weather').textContent = weatherString;
// Cache the weather data
localStorage.setItem('weatherData', JSON.stringify({
text: weatherString,
timestamp: now.toISOString()
}));
})
.catch(() => {
document.getElementById('weather').textContent = weatherText;
});
})
.catch(() => {
document.getElementById('weather').textContent = "Unable to fetch weather.";
});
}
function fetchWeatherByCity(city, tempUnit = 'celsius') {
const now = new Date();
const cachedWeather = localStorage.getItem('weatherData');
if (cachedWeather) {
const weatherData = JSON.parse(cachedWeather);
if ((now - new Date(weatherData.timestamp)) < 30 * 60 * 1000) {
document.getElementById('weather').textContent = weatherData.text;
return;
}
}
fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(city)}`)
.then(res => res.json())
.then(data => {
if (data.length > 0) {
const { lat, lon } = data[0];
fetchWeatherAndCity(lat, lon, tempUnit);
} else {
document.getElementById('weather').textContent = "City not found";
}
})
.catch(() => {
document.getElementById('weather').textContent = "Unable to fetch weather";
});
}
function displayPhotoCredit(photoData) {
const creditContainer = document.getElementById('photo-credit');
const creditLink = document.getElementById('photo-credit-link');
if (photoData && photoData.user) {
creditLink.href = photoData.user.links.html + "?utm_source=minimal_new_tab&utm_medium=referral";
creditLink.textContent = photoData.user.name;
creditContainer.style.display = 'block';
} else {
creditContainer.style.display = 'none';
}
}
function analyzeAndSetTextColor(imageUrl) {
const img = new Image();
img.crossOrigin = "Anonymous";
img.src = imageUrl;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const x = Math.floor(img.width / 4);
const y = Math.floor(img.height / 4);
const width = Math.floor(img.width / 2);
const height = Math.floor(img.height / 2);
const imageData = ctx.getImageData(x, y, width, height).data;
let r = 0, g = 0, b = 0;
for (let i = 0; i < imageData.length; i += 4) {
r += imageData[i];
g += imageData[i + 1];
b += imageData[i + 2];
}
const pixelCount = imageData.length / 4;
const luminance = (0.299 * (r / pixelCount) + 0.587 * (g / pixelCount) + 0.114 * (b / pixelCount));
document.body.style.color = luminance > 128 ? '#222' : '#f0f0f0';
};
}
async function setUnsplashBackground(forceRefresh = false) {
const now = new Date();
const cachedData = localStorage.getItem('unsplashData');
const userApiKey = settings.unsplashApiKey;
let currentTheme = localStorage.getItem('theme') || 'system';
let themeQuery = '';
if (currentTheme === 'system') {
currentTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
if (currentTheme === 'dark') {
themeQuery = ',dark';
}
const frequencyMap = {
'15min': 15 * 60 * 1000,
'30min': 30 * 60 * 1000,
'hourly': 60 * 60 * 1000,
'daily': 24 * 60 * 60 * 1000,
'weekly': 7 * 24 * 60 * 60 * 1000
};
const updateFrequency = frequencyMap[settings.unsplashUpdateFrequency] || frequencyMap['daily'];
if (userApiKey && settings.showUnsplashRefresh) {
document.getElementById('refresh-background').style.display = 'inline-flex';
}
if (cachedData && !forceRefresh) {
const { timestamp, photo } = JSON.parse(cachedData);
if ((now - new Date(timestamp)) < updateFrequency) {
const img = new Image();
img.onload = () => {
document.body.style.backgroundImage = `url(${photo.urls.full})`;
analyzeAndSetTextColor(photo.urls.full);
};
img.src = photo.urls.full;
displayPhotoCredit(photo);
return;
}
}
if (!userApiKey) {
console.error("Unsplash API key is missing. Please add it in the options page.");
const creditContainer = document.getElementById('photo-credit');
creditContainer.style.display = 'block';
creditContainer.innerHTML = 'Unsplash background requires an API key in settings.';
return;
}
try {
let apiUrl;
if (userApiKey) {
const cacheBust = new Date().getTime();
apiUrl = `https://api.unsplash.com/photos/random?query=wallpapers${themeQuery}&orientation=landscape&client_id=${userApiKey}&cache_bust=${cacheBust}`;
}
const response = await fetch(apiUrl);
if (response.ok) {
const newPhoto = await response.json();
const img = new Image();
img.onload = () => {
document.body.style.backgroundImage = `url(${newPhoto.urls.full})`;
analyzeAndSetTextColor(newPhoto.urls.full);
localStorage.setItem('unsplashData', JSON.stringify({
timestamp: now.toISOString(),
photo: newPhoto
}));
displayPhotoCredit(newPhoto);
};
img.src = newPhoto.urls.full;
}
else if (response.status === 429) {
console.warn("Unsplash background refresh rate-limited. Please wait before trying again.");
}
} catch (error) {
console.error("Failed to fetch Unsplash background:", error);
}
}
function applyTheme(theme) {
document.body.classList.remove('dark', 'light');
if (theme === 'dark') {
document.body.classList.add('dark');
} else if (theme === 'light') {
document.body.classList.add('light');
} else {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.body.classList.add('dark');
} else {
document.body.classList.add('light');
}
}
const iconContainer = document.querySelector('.theme-icon');
const label = document.querySelector('.theme-label');
iconContainer.innerHTML = icons[theme];
label.textContent = theme[0].toUpperCase() + theme.slice(1);
const customizeContainer = document.querySelector('.customize-icon');
if (theme == 'system') {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
customizeContainer.innerHTML = customizeIcon["dark"];
}
else {
customizeContainer.innerHTML = customizeIcon["light"];
}
}
else {
customizeContainer.innerHTML = customizeIcon[theme];
}
}
function renderBookmarks(nodes, container, level = 0, path = "") {
nodes.forEach(node => {
const currentPath = `${path}/${node.title || "Untitled"}`;
if (node.children && node.children.length > 0) {
const listItem = document.createElement('li');
listItem.className = 'bookmark-folder-item';
const folderButton = document.createElement('button');
folderButton.type = 'button';
folderButton.className = 'bookmark-folder';
const chevron = document.createElement('span');
chevron.className = 'chevron';
chevron.textContent = '▶';
const title = document.createElement('span');
title.textContent = ` ${node.title || "Untitled folder"}`;
folderButton.appendChild(chevron);
folderButton.appendChild(title);
const childrenList = document.createElement('ul');
childrenList.className = 'bookmark-children';
const isOpen = settings.expandBookmarks ? true : localStorage.getItem(currentPath) === "true";
if (isOpen) {
chevron.textContent = '▼';
} else {
childrenList.classList.add('collapsed');
}
folderButton.addEventListener('click', () => {
const isCollapsed = childrenList.classList.contains('collapsed');
if (isCollapsed) {
childrenList.classList.remove('collapsed');
chevron.textContent = '▼';
localStorage.setItem(currentPath, "true");
} else {
childrenList.classList.add('collapsed');
chevron.textContent = '▶';
localStorage.setItem(currentPath, "false");
}
});
listItem.appendChild(folderButton);
listItem.appendChild(childrenList);
container.appendChild(listItem);
renderBookmarks(node.children, childrenList, level + 1, currentPath);
} else if (node.url) {
const listItem = document.createElement('li');
listItem.className = 'bookmark-link-item';
const a = document.createElement('a');
a.href = node.url;
a.className = 'shortcut';
a.textContent = node.title || node.url;
listItem.appendChild(a);
container.appendChild(listItem);
}
});
}
if (localStorage.getItem("settings") === null) {
localStorage.setItem("settings", JSON.stringify(defaultSettings));
}
const settings = JSON.parse(localStorage.getItem("settings")) || defaultSettings;
// Apply custom CSS if provided
if (settings.customCSS) {
const styleElement = document.createElement('style');
styleElement.id = 'user-custom-css';
styleElement.textContent = settings.customCSS;
document.head.appendChild(styleElement);
}
if (settings.useUnsplash) {
setUnsplashBackground();
} else if (settings.backgroundImage) {
document.body.style.backgroundImage = `url(${settings.backgroundImage})`;
analyzeAndSetTextColor(settings.backgroundImage);
}
if (settings.useUnsplash || settings.backgroundImage) {
document.body.style.backgroundSize = "cover";
document.body.style.backgroundPosition = "center";
}
if (settings.clock) {
setInterval(updateClock, 1000);
updateClock();
}
else {
document.getElementById("clock").style.display = 'none';
}
if (settings.autoHide) {
document.body.classList.add('auto-hide');
document.addEventListener('mousemove', (e) => {
const threshold = 100;
if (window.innerHeight - e.clientY < threshold) {
document.body.classList.add('controls-visible');
} else {
document.body.classList.remove('controls-visible');
}
});
}
if (settings.weather) {
const useCustomCity = settings.useCustomCity;
const tempUnit = settings.tempUnit || 'celsius';
if (useCustomCity && settings.customCity) {
const customCity = settings.customCity;
fetchWeatherByCity(customCity, tempUnit);
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
pos => fetchWeatherAndCity(pos.coords.latitude, pos.coords.longitude, tempUnit),
() => {
setTimeout(() => {
navigator.geolocation.getCurrentPosition(
pos => fetchWeatherAndCity(pos.coords.latitude, pos.coords.longitude, tempUnit),
() => document.getElementById('weather').textContent = "Location access denied."
);
}, 100);
}
);
} else {
document.getElementById('weather').textContent = "Geolocation not supported.";
}
}
} else {
document.getElementById('weather').style.display = 'none';
}
if (settings.bookmarks) {
chrome.bookmarks.getTree(tree => {
const shortcuts = document.getElementById('shortcuts');
let bookmarksBar = settings.bookmarkFolder?.trim()
? tree[0].children.find(f => f.title.toLowerCase() === settings.bookmarkFolder.toLowerCase())
: tree[0].children[0];
if (settings.bookmarkFolder?.trim() && !bookmarksBar) {
shortcuts.textContent = "Bookmark folder not found.";
return;
}
const listRoot = document.createElement('ul');
listRoot.className = 'bookmark-list';
shortcuts.innerHTML = '';
renderBookmarks(
settings.bookmarkFolder?.trim() ? bookmarksBar.children : tree[0].children,
listRoot
);
shortcuts.appendChild(listRoot);
});
} else {
document.getElementById("shortcuts").style.display = 'none';
}
if (settings.topRight) {
const topRightOrder = settings.topRightOrder;
let container = document.getElementById("top-right");
container.innerHTML = "";
topRightOrder.map((item) => {
if (item.displayBool) {
let itemElem = document.createElement("span");
itemElem.id = "open-" + item["id"];
itemElem.innerHTML = item["id"];
itemElem.addEventListener('click', () => {
chrome.tabs.create({ url: item['url'] });
})
container.append(itemElem);
}
})
}
else {
document.getElementById('top-right').style.display = 'none';
}
if (settings.sidebar) {
const sidebar = document.getElementById('sidebar');
sidebar.style.display = 'flex';
sidebar.classList.add(settings.sidebarPosition || 'right');
const sidebarContent = sidebar.querySelector('.sidebar-content');
const selectedWidgets = settings.sidebarWidgets || [];
const widgetRenderers = {
calendar: renderCalendar,
todo: renderTodo
};
if (selectedWidgets.length > 0) {
selectedWidgets.forEach(widgetId => {
if (widgetRenderers[widgetId]) {
const widgetContainer = document.createElement('div');
widgetContainer.classList.add('widget');
widgetContainer.id = `widget-${widgetId}`;
const widgetContent = widgetRenderers[widgetId];
widgetContainer.append(widgetContent());
sidebarContent.appendChild(widgetContainer);
}
});
} else {
sidebarContent.innerHTML = '<p style="text-align: center; margin-top: 50px;">No widgets selected. You can add widgets from the Customize menu.</p>';
}
if (settings.sidebarExpanded) {
sidebar.classList.remove('minimised');
}
if (settings.sidebarShowCustomize || settings.sidebarExpanded) {
const sidebarFooter = document.createElement('div');
sidebarFooter.className = 'sidebar-footer';
sidebarFooter.innerHTML = `<button id="sidebar-customize" class="sidebar-customize-btn" title="Customize">Customize</button>`;
sidebar.appendChild(sidebarFooter);
document.getElementById('sidebar-customize').addEventListener('click', () => {
location.href = '/options.html';
});
}
// Hide/show bottom-left customize button based on sidebar position and state
const customizeBtn = document.getElementById('customize');
const themeToggle = document.querySelector('.theme-toggle');
const updateCustomizeVisibility = () => {
const isLeft = settings.sidebarPosition === 'left';
const isRight = settings.sidebarPosition === 'right' || !settings.sidebarPosition;
const isExpanded = !sidebar.classList.contains('minimised');
// Hide customize button when sidebar is on left and expanded
if (isLeft && isExpanded) {
customizeBtn.style.opacity = '0';
customizeBtn.style.pointerEvents = 'none';
} else {
customizeBtn.style.opacity = '1';
customizeBtn.style.pointerEvents = 'auto';
}
// Hide theme toggle when sidebar is on right and expanded
if (isRight && isExpanded) {
themeToggle.style.opacity = '0';
themeToggle.style.pointerEvents = 'none';
} else {
themeToggle.style.opacity = '1';
themeToggle.style.pointerEvents = 'auto';
}
};
updateCustomizeVisibility();
const handle = sidebar.querySelector('.sidebar-handle');
handle.addEventListener('click', () => {
sidebar.classList.toggle('minimised');
updateCustomizeVisibility();
});
}
if (settings.unsplashApiKey && settings.showUnsplashRefresh) {
document.getElementById('refresh-background').addEventListener('click', () => {
setUnsplashBackground(true);
});
}
const icons = {
system: `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"> <defs> <linearGradient id="half"> <stop offset="50%" stop-color="white" /> <stop offset="50%" stop-color="black" /> </linearGradient> </defs> <circle cx="24" cy="24" r="10" fill="url(#half)" stroke="currentColor" stroke-width="2"/> <line x1="24" y1="2" x2="24" y2="10" stroke="currentColor" stroke-width="2"/> <line x1="24" y1="38" x2="24" y2="46" stroke="currentColor" stroke-width="2"/> <line x1="2" y1="24" x2="10" y2="24" stroke="currentColor" stroke-width="2"/> <line x1="38" y1="24" x2="46" y2="24" stroke="currentColor" stroke-width="2"/> <line x1="8.5" y1="8.5" x2="14.5" y2="14.5" stroke="currentColor" stroke-width="2"/> <line x1="33.5" y1="33.5" x2="39.5" y2="39.5" stroke="currentColor" stroke-width="2"/> <line x1="8.5" y1="39.5" x2="14.5" y2="33.5" stroke="currentColor" stroke-width="2"/> <line x1="33.5" y1="14.5" x2="39.5" y2="8.5" stroke="currentColor" stroke-width="2"/> </svg>`,
dark: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path fill="none" stroke="white" d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 1 0 9.79 9.79Z"/> </svg>`,
light: `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" fill="none" stroke="black" stroke-width="2"> <circle cx="24" cy="24" r="10" fill="none"/> <line x1="24" y1="2" x2="24" y2="10"/> <line x1="24" y1="38" x2="24" y2="46"/> <line x1="2" y1="24" x2="10" y2="24"/> <line x1="38" y1="24" x2="46" y2="24"/> <line x1="8.5" y1="8.5" x2="14.5" y2="14.5"/> <line x1="33.5" y1="33.5" x2="39.5" y2="39.5"/> <line x1="8.5" y1="39.5" x2="14.5" y2="33.5"/> <line x1="33.5" y1="14.5" x2="39.5" y2="8.5"/> </svg>`
};
const customizeIcon = {
"dark": `<svg fill="white" width="32px" height="32px" viewBox="-1 0 44 44"><path id="_45.Settings" data-name="45.Settings" d="M35,22H13A10,10,0,0,1,13,2H35a10,10,0,0,1,0,20ZM35,4H13a8,8,0,0,0,0,16H35A8,8,0,0,0,35,4ZM13,18a6,6,0,1,1,6-6A6,6,0,0,1,13,18ZM13,8a4,4,0,1,0,4,4A4,4,0,0,0,13,8Zm0,18H35a10,10,0,0,1,0,20H13a10,10,0,0,1,0-20Zm0,18H35a8,8,0,0,0,0-16H13a8,8,0,0,0,0,16ZM35,30a6,6,0,1,1-6,6A6,6,0,0,1,35,30Zm0,10a4,4,0,1,0-4-4A4,4,0,0,0,35,40Z" transform="translate(-3 -2)" fill-rule="evenodd"/></svg>`,
"light": `<svg fill="black" width="32px" height="32px" viewBox="-1 0 44 44"><path id="_45.Settings" data-name="45.Settings" d="M35,22H13A10,10,0,0,1,13,2H35a10,10,0,0,1,0,20ZM35,4H13a8,8,0,0,0,0,16H35A8,8,0,0,0,35,4ZM13,18a6,6,0,1,1,6-6A6,6,0,0,1,13,18ZM13,8a4,4,0,1,0,4,4A4,4,0,0,0,13,8Zm0,18H35a10,10,0,0,1,0,20H13a10,10,0,0,1,0-20Zm0,18H35a8,8,0,0,0,0-16H13a8,8,0,0,0,0,16ZM35,30a6,6,0,1,1-6,6A6,6,0,0,1,35,30Zm0,10a4,4,0,1,0-4-4A4,4,0,0,0,35,40Z" transform="translate(-3 -2)" fill-rule="evenodd"/></svg>`
}
document.getElementById("customize").addEventListener("click", () => {
location.href = "/options.html";
})
// Initialize theme
let theme = localStorage.getItem('theme') || 'system';
applyTheme(theme);
// Handle toggle click
document.querySelector('.theme-toggle').addEventListener('click', () => {
if (theme === 'system') {
theme = 'dark';
} else if (theme === 'dark') {
theme = 'light';
} else {
theme = 'system';
}
localStorage.setItem('theme', theme);
applyTheme(theme);
});
// React to system theme change if in system mode
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
if (theme === 'system') {
applyTheme('system');
}
});