-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewtab.js
More file actions
493 lines (430 loc) · 15.5 KB
/
Copy pathnewtab.js
File metadata and controls
493 lines (430 loc) · 15.5 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
'use strict';
const STORAGE_KEY = 'startdock';
const DEFAULT_DATA = {
categories: [
{
name: 'Search & Productivity', color: '#10B981',
bookmarks: [
{ name: 'Google', url: 'https://www.google.com' },
{ name: 'Gmail', url: 'https://mail.google.com' },
{ name: 'Google Drive', url: 'https://drive.google.com' },
{ name: 'Google Docs', url: 'https://docs.google.com' },
{ name: 'Calendar', url: 'https://calendar.google.com' },
],
},
{
name: 'Development', color: '#F59E0B',
bookmarks: [
{ name: 'GitHub', url: 'https://github.com' },
{ name: 'Stack Overflow', url: 'https://stackoverflow.com' },
{ name: 'MDN Web Docs', url: 'https://developer.mozilla.org' },
{ name: 'npm', url: 'https://www.npmjs.com' },
{ name: 'Can I Use', url: 'https://caniuse.com' },
],
},
{
name: 'AI Tools', color: '#8B5CF6',
bookmarks: [
{ name: 'Claude', url: 'https://claude.ai' },
{ name: 'ChatGPT', url: 'https://chatgpt.com' },
{ name: 'Gemini', url: 'https://gemini.google.com' },
{ name: 'Perplexity', url: 'https://www.perplexity.ai' },
],
},
{
name: 'Design', color: '#EC4899',
bookmarks: [
{ name: 'Figma', url: 'https://figma.com' },
{ name: 'Canva', url: 'https://www.canva.com' },
{ name: 'SVG Repo', url: 'https://www.svgrepo.com' },
{ name: 'Favicon.io', url: 'https://favicon.io' },
{ name: 'Internet Archive', url: 'https://archive.org/web' },
],
},
{
name: 'Social & News', color: '#3B82F6',
bookmarks: [
{ name: 'Reddit', url: 'https://www.reddit.com' },
{ name: 'Hacker News', url: 'https://news.ycombinator.com' },
{ name: 'X / Twitter', url: 'https://x.com' },
{ name: 'LinkedIn', url: 'https://www.linkedin.com' },
{ name: 'YouTube', url: 'https://www.youtube.com' },
],
},
{
name: 'Entertainment', color: '#64748B',
bookmarks: [
{ name: 'Netflix', url: 'https://www.netflix.com' },
{ name: 'Spotify', url: 'https://open.spotify.com' },
{ name: 'Twitch', url: 'https://www.twitch.tv' },
],
},
],
};
/* ── Native bookmark helpers ── */
const CATEGORY_COLORS = [
'#3B82F6','#10B981','#F59E0B','#EF4444',
'#8B5CF6','#EC4899','#06B6D4','#64748B',
];
function flattenNode(node, pathParts, showPath) {
const bookmarks = [];
if (!node.children) return bookmarks;
for (const child of node.children) {
if (child.url) {
const pathLabel = pathParts.filter(Boolean).join(' / ');
const name = showPath && pathLabel
? pathLabel + ' / ' + (child.title || child.url)
: (child.title || child.url);
bookmarks.push({ name, url: child.url });
} else {
const nextPath = child.title ? [...pathParts, child.title] : pathParts;
bookmarks.push(...flattenNode(child, nextPath, showPath));
}
}
return bookmarks;
}
function nativeBookmarksToCategories(tree, showPath) {
const categories = [];
let colorIdx = 0;
function processRoot(rootNode) {
if (!rootNode.children) return;
const directBookmarks = rootNode.children
.filter(c => c.url)
.map(c => ({ name: c.title || c.url, url: c.url }));
if (directBookmarks.length > 0) {
categories.push({
name: rootNode.title,
color: CATEGORY_COLORS[colorIdx++ % CATEGORY_COLORS.length],
bookmarks: directBookmarks,
});
}
rootNode.children.filter(c => !c.url).forEach(folder => {
const bookmarks = flattenNode(folder, [], showPath);
if (bookmarks.length > 0) {
categories.push({
name: folder.title || 'Folder',
color: CATEGORY_COLORS[colorIdx++ % CATEGORY_COLORS.length],
bookmarks,
});
}
});
}
if (tree[0] && tree[0].children) {
tree[0].children.forEach(processRoot);
}
return categories;
}
function loadNativeBookmarks(showPath) {
return new Promise(resolve => {
if (!chrome.bookmarks) { resolve(null); return; }
chrome.bookmarks.getTree(tree => {
if (chrome.runtime.lastError || !tree) { resolve(null); return; }
resolve(nativeBookmarksToCategories(tree, showPath));
});
});
}
let currentSettings = {};
/* ── Utilities ── */
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `${r}, ${g}, ${b}`;
}
function faviconUrl(url) {
try {
const domain = new URL(url).hostname;
return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
} catch {
return '';
}
}
function loadBgImage() {
return new Promise(resolve => {
chrome.storage.local.get('startdock_bg', r => resolve(r.startdock_bg || null));
});
}
function setBackground(url) {
const overlay = 'linear-gradient(rgba(11,13,20,0.5),rgba(11,13,20,0.5))';
document.body.style.backgroundImage = `${overlay}, url("${url}")`;
document.body.style.backgroundSize = 'auto, cover';
document.body.style.backgroundPosition = 'top left, center center';
document.body.style.backgroundAttachment = 'fixed, fixed';
document.body.style.backgroundRepeat = 'repeat, no-repeat';
}
function clearBackground() {
document.body.style.backgroundImage = '';
document.body.style.backgroundSize = '';
document.body.style.backgroundPosition = '';
document.body.style.backgroundAttachment = '';
document.body.style.backgroundRepeat = '';
}
async function applyBackground(settings) {
const mode = settings.backgroundMode || 'none';
if (mode === 'none') { clearBackground(); return; }
if (mode === 'uploaded') {
const dataUrl = await loadBgImage();
if (dataUrl) setBackground(dataUrl); else clearBackground();
return;
}
if (mode === 'random') {
const seed = settings.refreshBgOnOpen ? Date.now() : (settings.randomBgSeed || 42);
setBackground(`https://picsum.photos/seed/${seed}/1920/1080`);
}
}
function applyCardTransparency(settings) {
const hasImage = (settings.backgroundMode || 'none') !== 'none';
const opacity = (hasImage && settings.cardTransparency)
? ((settings.cardOpacity ?? 85) / 100)
: 1;
document.documentElement.style.setProperty('--card-opacity', opacity);
}
function loadData() {
return new Promise(resolve => {
chrome.storage.sync.get(STORAGE_KEY, result => {
resolve(result[STORAGE_KEY] || null);
});
});
}
function saveData(data) {
return new Promise(resolve => {
chrome.storage.sync.set({ [STORAGE_KEY]: data }, resolve);
});
}
/* ── Render ── */
function renderGrid(categories, maxVisible) {
const grid = document.getElementById('grid');
grid.innerHTML = '';
categories.forEach((cat, i) => {
grid.appendChild(buildColumn(cat, i, maxVisible));
});
}
function buildColumn(cat, index, maxVisible) {
const rgb = hexToRgb(cat.color);
const col = document.createElement('div');
col.className = 'column';
col.style.cssText = `--accent: ${cat.color}; --accent-rgb: ${rgb}; animation-delay: ${index * 40}ms`;
const header = document.createElement('div');
header.className = 'column-header';
const bmCount = cat.bookmarks.filter(bm => bm.type !== 'separator').length;
header.innerHTML = `
<span class="column-dot"></span>
<h2 class="column-title">${escHtml(cat.name)}</h2>
<span class="column-count">${bmCount}</span>
`;
const list = document.createElement('div');
list.className = 'bookmark-list';
const limit = (maxVisible && maxVisible > 0) ? maxVisible : null;
let visibleCount = 0;
const hiddenItems = [];
cat.bookmarks.forEach(bm => {
const el = buildBookmark(bm);
if (limit && bm.type !== 'separator' && visibleCount >= limit) {
el.classList.add('hidden');
hiddenItems.push(el);
} else {
if (bm.type !== 'separator') visibleCount++;
}
list.appendChild(el);
});
col.appendChild(header);
col.appendChild(list);
if (hiddenItems.length > 0) {
const expandBtn = document.createElement('button');
expandBtn.className = 'col-expand-btn';
expandBtn.title = 'Show more';
expandBtn.innerHTML = `<span class="col-expand-icon"></span><span class="col-expand-label">${hiddenItems.length} more</span>`;
expandBtn.addEventListener('click', () => {
const expanded = expandBtn.classList.toggle('expanded');
hiddenItems.forEach(el => el.classList.toggle('hidden', !expanded));
expandBtn.querySelector('.col-expand-label').textContent = expanded ? 'Show less' : `${hiddenItems.length} more`;
});
col.appendChild(expandBtn);
}
return col;
}
function buildBookmark(bm) {
if (bm.type === 'separator') {
const wrap = document.createElement('div');
wrap.className = 'bookmark-separator';
if (bm.label) {
wrap.classList.add('bookmark-separator--labeled');
wrap.innerHTML = `<span>${escHtml(bm.label)}</span>`;
}
return wrap;
}
const a = document.createElement('a');
a.className = 'bookmark-item';
a.href = bm.url;
a.innerHTML = `
<img class="favicon" src="${faviconUrl(bm.url)}" alt="" loading="lazy" onerror="this.style.display='none'">
<span class="bookmark-name">${escHtml(bm.name)}</span>
`;
return a;
}
function escHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function updateStats(categories) {
const total = categories.reduce((s, c) => s + c.bookmarks.filter(bm => bm.type !== 'separator').length, 0);
document.getElementById('bookmark-total').textContent = total;
document.getElementById('category-total').textContent = categories.length;
}
/* ── Clock & date ── */
const DAYS = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
const MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function pad(n) { return String(n).padStart(2, '0'); }
function greeting(h) {
if (h < 12) return 'Good morning';
if (h < 17) return 'Good afternoon';
return 'Good evening';
}
function tick() {
const now = new Date();
const h = now.getHours(), m = now.getMinutes(), s = now.getSeconds();
document.getElementById('clock-hm').textContent = pad(h) + ':' + pad(m);
document.getElementById('clock-s').textContent = ':' + pad(s);
document.getElementById('greeting').textContent = greeting(h);
document.getElementById('date-line').textContent =
DAYS[now.getDay()] + ', ' + MONTHS[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear();
}
function initClock() {
tick();
setInterval(tick, 1000);
}
/* ── Calendar ── */
function initCalendar() {
const today = new Date();
let calYear = today.getFullYear();
let calMonth = today.getMonth();
function render(year, month) {
document.getElementById('cal-month-label').textContent = MONTHS_SHORT[month] + ' ' + year;
const grid = document.getElementById('cal-grid');
grid.innerHTML = '';
['Su','Mo','Tu','We','Th','Fr','Sa'].forEach(d => {
const el = document.createElement('div');
el.className = 'cal-dow';
el.textContent = d;
grid.appendChild(el);
});
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const isCurrent = year === today.getFullYear() && month === today.getMonth();
for (let i = 0; i < firstDay; i++) {
const el = document.createElement('div');
el.className = 'cal-day empty';
grid.appendChild(el);
}
for (let d = 1; d <= daysInMonth; d++) {
const el = document.createElement('div');
el.className = 'cal-day' + (isCurrent && d === today.getDate() ? ' today' : '');
el.textContent = d;
grid.appendChild(el);
}
}
render(calYear, calMonth);
document.getElementById('cal-prev').addEventListener('click', () => {
calMonth--; if (calMonth < 0) { calMonth = 11; calYear--; }
render(calYear, calMonth);
});
document.getElementById('cal-next').addEventListener('click', () => {
calMonth++; if (calMonth > 11) { calMonth = 0; calYear++; }
render(calYear, calMonth);
});
}
/* ── Search ── */
function initSearch() {
const input = document.getElementById('search');
const noResults = document.getElementById('no-results');
function doSearch(q) {
const term = q.trim().toLowerCase();
let anyVisible = false;
document.querySelectorAll('.column').forEach(col => {
let colVisible = false;
col.querySelectorAll('.bookmark-item').forEach(item => {
const name = item.querySelector('.bookmark-name').textContent.toLowerCase();
const match = !term || name.includes(term);
item.classList.toggle('hidden', !match);
if (match) colVisible = true;
});
col.classList.toggle('hidden', !colVisible);
if (colVisible) anyVisible = true;
});
noResults.style.display = (!anyVisible && term) ? 'block' : 'none';
document.getElementById('search-hint').style.display = term ? 'none' : '';
}
input.addEventListener('input', e => doSearch(e.target.value));
document.addEventListener('keydown', e => {
if (e.key === '/' && document.activeElement !== input) {
e.preventDefault();
input.focus();
input.select();
}
if (e.key === 'Escape' && document.activeElement === input) {
input.value = '';
doSearch('');
input.blur();
}
});
}
/* ── Settings button ── */
function initSettings() {
document.getElementById('settings-btn').addEventListener('click', () => {
chrome.runtime.openOptionsPage();
});
}
/* ── Storage change listener (live updates when options page saves) ── */
chrome.storage.onChanged.addListener((changes, area) => {
if (area === 'sync' && changes[STORAGE_KEY]) {
const data = changes[STORAGE_KEY].newValue;
if (!data) return;
currentSettings = data.settings || {};
const maxVisible = currentSettings.maxVisible || null;
if (currentSettings.dataSource === 'native') {
loadNativeBookmarks(currentSettings.nativeShowPath || false).then(nativeCategories => {
const categories = nativeCategories !== null ? nativeCategories : data.categories;
renderGrid(categories, maxVisible);
updateStats(categories);
});
} else {
renderGrid(data.categories, maxVisible);
updateStats(data.categories);
}
applyBackground(currentSettings);
applyCardTransparency(currentSettings);
}
if (area === 'local' && changes['startdock_bg']) {
if ((currentSettings.backgroundMode || 'none') === 'uploaded') {
const newVal = changes['startdock_bg'].newValue;
if (newVal) setBackground(newVal); else clearBackground();
}
}
});
/* ── Init ── */
async function init() {
let data = await loadData();
if (!data) {
data = DEFAULT_DATA;
await saveData(data);
}
const settings = data.settings || {};
currentSettings = settings;
const maxVisible = settings.maxVisible || null;
let categories;
if (settings.dataSource === 'native') {
const nativeCategories = await loadNativeBookmarks(settings.nativeShowPath || false);
categories = nativeCategories !== null ? nativeCategories : data.categories;
} else {
categories = data.categories;
}
renderGrid(categories, maxVisible);
updateStats(categories);
await applyBackground(settings);
applyCardTransparency(settings);
initClock();
initCalendar();
initSearch();
initSettings();
}
init();