-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignpost.js
More file actions
602 lines (534 loc) · 22 KB
/
signpost.js
File metadata and controls
602 lines (534 loc) · 22 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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
document.addEventListener('DOMContentLoaded', () => {
// Set how content is applied to widgets
GridStack.renderCB = function (el, w) {
el.innerHTML = w.content;
if (w.backgroundColor) {
const content = el.querySelector('.tile');
if (content) content.style.backgroundColor = w.backgroundColor;
}
if (w.textColor) {
const content = el.querySelector('.tile');
if (content) content.style.color = w.textColor;
}
};
const gridOptions = {
column: 18,
float: true,
margin: 6,
minRow: 5
}
const grid = GridStack.init(gridOptions);
// Save layout on changes
grid.on('change', saveLayout);
// Load layout on startup from LOCAL, show first-run setup if empty
chrome.storage.local.get({ tiles: [], setupComplete: false }, (loc) => {
let { tiles, setupComplete } = loc;
if (tiles && tiles.length > 0) {
renderTiles(tiles);
} else {
handleEmpty(setupComplete);
}
});
function renderTiles(tiles) {
tiles.forEach(tile => {
chrome.bookmarks.getSubTree(String(tile.id), (results) => {
if (results && results[0]) addTileToGrid(results[0], tile);
});
});
}
// --- Initial Setup Modal ---
const setupModal = document.getElementById('setup-prompt');
const btnLoadFromBar = document.getElementById('load-bookmarks');
const btnStartEmpty = document.getElementById('start-empty');
function handleEmpty(setupComplete) {
if (!setupComplete) {
openModal(setupModal);
} else {
// reset flag if user somehow has setupComplete but no tiles
chrome.storage.local.set({ setupComplete: false });
openModal(setupModal);
}
}
btnLoadFromBar?.addEventListener('click', async () => {
// Import top-level items from the Bookmarks Bar
chrome.bookmarks.getSubTree('1', (results) => {
const bar = results && results[0];
if (!bar) {
alert('Could not access Bookmarks Bar.');
return;
}
const children = bar.children || [];
if (!children.length) {
showBubbleMessage('Bookmarks Bar is empty');
}
// Batch add for smoother GridStack updates
if (grid.batchUpdate) grid.batchUpdate();
children.forEach(child => addTileToGrid(child));
if (grid.batchUpdate) grid.batchUpdate(false);
saveLayout();
chrome.storage.local.set({ setupComplete: true });
closeModal(setupModal);
showBubbleMessage('Imported from Bookmarks Bar');
});
});
btnStartEmpty?.addEventListener('click', () => {
chrome.storage.local.set({ setupComplete: true });
closeModal(setupModal);
showBubbleMessage('Start with an empty grid');
});
const defaultSettings = {
openInNewTab: false,
confirmBeforeRemove: false,
tileSize: 140,
desktopBackgroundColor: '#ffffff',
desktopBackgroundImage: null
};
let globalSettings = { ...defaultSettings };
const openInNewTabCheckbox = document.getElementById('setting-new-tab');
const confirmBeforeRemoveCheckbox = document.getElementById('setting-confirm-remove');
const backgroundColorInput = document.getElementById('setting-background-color');
const backgroundImageInput = document.getElementById('setting-background-image');
const clearBackgroundBtn = document.getElementById('clear-background');
const resetSettingsBtn = document.getElementById('reset-settings');
// Load and apply settings
chrome.storage.local.get('globalSettings', (data) => {
Object.assign(globalSettings, data.globalSettings || {});
openInNewTabCheckbox.checked = globalSettings.openInNewTab;
confirmBeforeRemoveCheckbox.checked = globalSettings.confirmBeforeRemove;
backgroundColorInput.value = globalSettings.desktopBackgroundColor;
document.body.style.backgroundColor = globalSettings.desktopBackgroundColor;
});
chrome.storage.local.get('desktopBackgroundImage', (data) => {
if (data.desktopBackgroundImage) {
document.body.style.backgroundImage = `url(${data.desktopBackgroundImage})`;
document.body.style.backgroundSize = 'cover';
document.body.style.backgroundPosition = 'center';
}
});
// Save updated settings on change
openInNewTabCheckbox.addEventListener('change', () => {
globalSettings.openInNewTab = openInNewTabCheckbox.checked;
chrome.storage.local.set({ globalSettings });
});
confirmBeforeRemoveCheckbox.addEventListener('change', () => {
globalSettings.confirmBeforeRemove = confirmBeforeRemoveCheckbox.checked;
chrome.storage.local.set({ globalSettings });
});
backgroundColorInput.addEventListener('input', () => {
globalSettings.desktopBackgroundColor = backgroundColorInput.value;
document.body.style.backgroundColor = backgroundColorInput.value;
chrome.storage.local.set({ globalSettings });
});
backgroundImageInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file || file.size > 2.5 * 1024 * 1024) {
alert("Image too large (max 2.5 MB)");
return;
}
const reader = new FileReader();
reader.onload = () => {
const desktopBackgroundImage = reader.result;
document.body.style.backgroundImage = `url(${desktopBackgroundImage})`;
document.body.style.backgroundSize = 'cover';
document.body.style.backgroundPosition = 'center';
chrome.storage.local.set({ desktopBackgroundImage: desktopBackgroundImage });
};
reader.readAsDataURL(file);
});
clearBackgroundBtn.addEventListener('click', () => {
document.body.style.backgroundImage = '';
backgroundImageInput.value = ''; // ← clears the input field
chrome.storage.local.remove('desktopBackgroundImage');
});
resetSettingsBtn.addEventListener('click', () => {
Object.assign(globalSettings, defaultSettings);
// Apply UI changes
openInNewTabCheckbox.checked = globalSettings.openInNewTab;
confirmBeforeRemoveCheckbox.checked = globalSettings.confirmBeforeRemove;
backgroundColorInput.value = globalSettings.desktopBackgroundColor;
document.body.style.backgroundColor = globalSettings.desktopBackgroundColor;
backgroundImageInput.value = '';
document.body.style.backgroundImage = '';
// Clear local image
chrome.storage.local.remove('desktopBackgroundImage');
// Save new defaults
chrome.storage.local.set({ globalSettings });
});
// Set up buttons and modals
const btnAdd = document.getElementById('btn-add');
const btnSettings = document.getElementById('btn-settings');
const modalAdd = document.getElementById('bookmark-picker');
const modalSet = document.getElementById('settings-panel');
btnAdd.addEventListener('click', () => {
if (!modalAdd) return;
const isVisible = !modalAdd.classList.contains('hidden');
if (isVisible) {
closeModal(modalAdd);
} else {
closeModal(modalSet);
openModal(modalAdd);
loadBookmarks();
}
});
btnSettings.addEventListener('click', () => {
if (!modalSet) return;
const isVisible = !modalSet.classList.contains('hidden');
if (isVisible) {
closeModal(modalSet);
} else {
closeModal(modalAdd);
openModal(modalSet);
}
});
document.querySelectorAll('.modal .btn-close').forEach(btn =>
btn.addEventListener('click', () => closeModal(btn.closest('.modal')))
);
document.querySelector('#settings-panel .btn-close')?.addEventListener('click', () => {
modalSet.classList.remove('visible');
closeModal(modalSet);
});
function openModal(modal) {
if (!modal) return;
modal.classList.remove('hidden');
document.body.classList.add('modal-open');
}
function closeModal(modal) {
if (!modal) return;
modal.classList.add('hidden');
if (document.querySelectorAll('.modal:not(.hidden)').length === 0) {
document.body.classList.remove('modal-open');
}
}
// Saving layout
function saveLayout() {
const layout = grid.engine.nodes.map(node => {
return {
x: node.x,
y: node.y,
w: node.w,
h: node.h,
id: node.id,
backgroundColor: node.backgroundColor || node.el?.querySelector('.tile')?.style.backgroundColor || '',
textColor: node.textColor || node.el?.querySelector('.folder-title')?.style.color || ''
};
});
chrome.storage.local.set({ tiles: layout });
}
function loadBookmarks() {
chrome.bookmarks.getTree(([root]) => {
const container = document.getElementById('bookmark-tree');
container.innerHTML = '';
container.appendChild(createTree(root.children));
});
}
function showBubbleMessage(text, duration = 2000) {
const bubble = document.getElementById('bubble-message');
bubble.textContent = text;
bubble.classList.remove('hidden');
setTimeout(() => {
bubble.classList.add('hidden');
}, duration);
}
function getFavicon(url, size = 32) {
const u = new URL(chrome.runtime.getURL('/_favicon/'));
u.searchParams.set('pageUrl', url);
u.searchParams.set('size', String(size));
return u.toString();
}
function createTree(nodes) {
const ul = document.createElement('ul');
nodes.forEach(node => {
const li = document.createElement('li');
if (node.children) {
const expandBtn = document.createElement('span');
expandBtn.textContent = '[+] ';
expandBtn.style.cursor = 'pointer';
expandBtn.style.marginRight = '4px';
const folderSpan = document.createElement('span');
folderSpan.textContent = `📁 ${node.title}`;
folderSpan.style.cursor = 'pointer';
folderSpan.style.fontWeight = 'bold';
const childUl = createTree(node.children);
childUl.style.display = 'none';
expandBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isHidden = childUl.style.display === 'none';
childUl.style.display = isHidden ? 'block' : 'none';
expandBtn.textContent = isHidden ? '[−] ' : '[+] ';
});
folderSpan.addEventListener('click', (e) => {
e.stopPropagation();
addTileToGrid(node);
closeModal(modalAdd);
});
li.appendChild(expandBtn);
li.appendChild(folderSpan);
li.appendChild(childUl);
} else {
const faviconURL = getFavicon(node.url, 16);
li.innerHTML = `<img class="favicon-tree" src="${faviconURL}"/> ${node.title}`;
li.style.cursor = 'pointer';
li.addEventListener('click', (e) => {
e.stopPropagation();
addTileToGrid(node);
closeModal(modalAdd);
});
}
ul.appendChild(li);
});
return ul;
}
function addTileToGrid(bookmark, pos) {
// Check the widget isn't in the grid yet
const existingNode = grid.engine.nodes.find(n => n.id === `${bookmark.id}`);
if (existingNode) {
showBubbleMessage("Widget already present!");
const tileEl = existingNode.el;
if (tileEl) {
tileEl.classList.add('widget-flash');
tileEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
setTimeout(() => tileEl.classList.remove('widget-flash'), 1000);
}
return;
}
// Calculate position for new widgets
if (!pos) {
const w = 2, h = 2;
const gridWidth = grid.getColumn();
let x = 0, y = 0;
let found = false;
outer: for (y = 0; y < 100; y++) { // max 100 rows
for (x = 0; x <= gridWidth - w; x++) {
const collision = grid.engine.nodes.some(n =>
x < n.x + n.w &&
x + w > n.x &&
y < n.y + n.h &&
y + h > n.y
);
if (!collision) {
found = true;
break outer;
}
}
}
pos = { x, y, w, h };
}
// Compose tile HTML content
let tileHeaderHTML;
let tileBodyHTML;
let tileHeaderTitleText;
const openTarget = globalSettings.openInNewTab ? '_blank' : '_self';
if (!bookmark.url) { // FOLDERS
let childListHTML = '';
const children = bookmark.children || [];
children.forEach(child => {
let contentHTML = '';
if (child.url) {
// Bookmark link
const faviconURL = getFavicon(child.url, 16);
contentHTML = `
<a class="bookmark-link" href="${child.url}" title="${child.title}" target="${openTarget}">
<img class="favicon" src="${faviconURL}"/>
</a>
`;
} else {
// Folder
contentHTML = `
<span class="bookmark-link bookmark-folder" title="${child.title}" data-id="${child.id}">📁</span>
`;
}
childListHTML += `
<div class="bookmark-item">
${contentHTML}
</div>
`;
});
tileHeaderTitleText = `📁 ${bookmark.title}`;
tileBodyHTML = `
<div class="tile-body folder-content">
${childListHTML}
</div>
`;
} else { // LINKS
const faviconURL = getFavicon(bookmark.url, 32);
tileHeaderTitleText = "";
tileBodyHTML = `
<div class="tile-body center">
<a class="bookmark-link" href="${bookmark.url}" title="${bookmark.title}" target="${openTarget}">
<img class="favicon-large" src="${faviconURL}"/>
<div class="bookmark-title">${bookmark.title}</div>
</a>
</div>
`;
}
const textColorItem = !bookmark.url
? `<div class="tile-menu-item set-text-color">Set text color</div>`
: '';
tileHeaderHTML = `
<div class="tile-header">
<div class="folder-title">${tileHeaderTitleText}</div>
<div class="tile-menu-icon">⁝
<div class="tile-menu hidden">
<div class="tile-menu-item remove-tile">Remove</div>
<div class="tile-menu-item set-bg-color">Set background color</div>
<div class="tile-menu-item reset-bg-color">Reset background</div>
${textColorItem}
</div>
</div>
</div>
`;
const tileHTML = `
<div class="tile">
${tileHeaderHTML}
${tileBodyHTML}
</div>
`;
const widget = grid.addWidget({
x: pos.x, y: pos.y, w: pos.w, h: pos.h,
content: tileHTML,
id: `${bookmark.id}`,
backgroundColor: pos?.backgroundColor || '',
textColor: pos?.textColor || ''
});
requestAnimationFrame(() => {
if (pos?.backgroundColor) {
const content = widget.el?.querySelector('.tile');
if (content) content.style.backgroundColor = pos.backgroundColor;
}
if (!bookmark.url && pos?.textColor) {
const title = widget.el?.querySelector('.folder-title');
if (title) title.style.color = pos.textColor;
}
});
addWidgetListeners(!bookmark.url, widget);
saveLayout(); // Save every time a new tile is added
}
function addWidgetListeners(isFolder, tileEl) {
// Toggle menu on icon click
const icon = tileEl.querySelector('.tile-menu-icon');
const menu = tileEl.querySelector('.tile-menu');
icon?.addEventListener('click', (e) => {
e.stopPropagation();
if (menu) {
menu.classList.toggle('hidden');
if (!menu.classList.contains('hidden')) {
// Position menu relative to icon
const iconRect = icon.getBoundingClientRect();
const menuRect = menu.getBoundingClientRect();
const overflowRight = iconRect.left + menuRect.width > window.innerWidth;
menu.classList.remove('flip-left');
if (overflowRight) {
menu.classList.add('flip-left');
}
// Close on outside click
document.addEventListener('click', function outsideClick(ev) {
if (!menu.contains(ev.target) && ev.target !== icon) {
menu.classList.add('hidden');
document.removeEventListener('click', outsideClick);
}
});
}
}
});
// Remove widget on menu click
tileEl.querySelector('.remove-tile')?.addEventListener('click', () => {
if (!globalSettings.confirmBeforeRemove || confirm("Remove this widget?")) {
grid.removeWidget(tileEl);
saveLayout();
}
});
// Set widget background color
tileEl.querySelector('.set-bg-color')?.addEventListener('click', (e) => {
e.stopPropagation();
tileEl.querySelector('.tile-menu')?.classList.add('hidden');
openColorPicker((color) => {
const content = tileEl.querySelector('.tile');
if (content) content.style.backgroundColor = color;
const node = grid.engine.nodes.find(n => n.el === tileEl);
if (node) node.backgroundColor = color;
saveLayout();
});
});
// Reset background color
tileEl.querySelector('.reset-bg-color')?.addEventListener('click', (e) => {
e.stopPropagation();
const content = tileEl.querySelector('.tile');
if (content) {
content.style.backgroundColor = '';
}
const node = grid.engine.nodes.find(n => n.el === tileEl);
if (node) {
delete node.backgroundColor;
}
saveLayout();
tileEl.querySelector('.tile-menu')?.classList.add('hidden');
});
if (isFolder) {
// Set text color
tileEl.querySelector('.set-text-color')?.addEventListener('click', (e) => {
e.stopPropagation();
openColorPicker((color) => {
const title = tileEl.querySelector('.folder-title');
if (title) {
title.style.color = color;
}
const node = grid.engine.nodes.find(n => n.el === tileEl);
if (node) node.textColor = color;
saveLayout();
});
});
}
// Add click listeners to child folders
tileEl.querySelectorAll('.bookmark-folder').forEach(folderEl => {
folderEl.addEventListener('click', (e) => {
e.stopPropagation();
const folderId = folderEl.getAttribute('data-id');
const node = grid.engine.nodes.find(n => n.el === tileEl);
let x = 0, y = 0;
if (node) {
const gridWidth = grid.getColumn();
const proposedX = node.x + node.w;
const sameRowWidgets = grid.engine.nodes.filter(n =>
n.y < node.y + node.h && n.y + n.h > node.y
);
const overlapRight = sameRowWidgets.some(n =>
n.x < proposedX + 1 && n.x + n.w > proposedX
);
if (proposedX + 1 <= gridWidth && !overlapRight) {
x = proposedX;
y = node.y;
} else {
x = node.x;
y = node.y + node.h;
}
}
const widgetPos = { x, y, w: 1, h: 1 };
chrome.bookmarks.getSubTree(folderId, (results) => {
if (results && results[0]) {
addTileToGrid(results[0], widgetPos);
}
});
});
});
}
function openColorPicker(onChange) {
const picker = document.createElement('input');
picker.type = 'color';
picker.style.position = 'absolute';
picker.style.left = '-9999px';
picker.addEventListener('input', () => {
onChange(picker.value);
});
// Remove if user clicks away
const cleanup = () => {
document.body.removeChild(picker);
document.removeEventListener('click', handleClickOutside);
};
const handleClickOutside = (e) => {
if (e.target !== picker) cleanup();
};
document.addEventListener('click', handleClickOutside);
document.body.appendChild(picker);
picker.click();
}
});