Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
625 lines (563 loc) · 25.3 KB
/
Copy pathmain.js
File metadata and controls
625 lines (563 loc) · 25.3 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// ==UserScript==
// @name Hide Image Overlays
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Adds a button to hide images when hovered over.
// @match *://*/*
// @grant GM_xmlHttpRequest
// ==/UserScript==
(function () {
'use strict';
if (window.top !== window.self) return; // Don't run in iframes
// --- STORAGE ---
function getStoredRecords() {
return JSON.parse(localStorage.getItem('hiddenImageRecords') || '[]');
}
function saveStoredRecords(records) {
localStorage.setItem('hiddenImageRecords', JSON.stringify(records));
}
function storeRecord(checksum, url) {
const records = getStoredRecords();
if (!records.some(r => r.checksum === checksum)) {
// Create thumbnail and store record
createThumbnail(url).then(thumbnail => {
records.push({ checksum, url, thumbnail });
saveStoredRecords(records);
}).catch(error => {
console.error('Failed to create thumbnail:', error);
// Store without thumbnail if creation fails
records.push({ checksum, url, thumbnail: null });
saveStoredRecords(records);
});
}
}
function removeRecord(checksum) {
const records = getStoredRecords().filter(r => r.checksum !== checksum);
saveStoredRecords(records);
}
// --- HASHING ---
async function hashString(input) {
try {
// Fetch the actual image data
const response = await new Promise((resolve, reject) => {
GM_xmlHttpRequest({
method: 'GET',
url: input,
responseType: 'arraybuffer',
onload: function(response) {
resolve(response.response);
},
onerror: function(error) {
reject(error);
}
});
});
// Hash the actual image data
const hashBuffer = await crypto.subtle.digest('SHA-256', response);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (error) {
console.error('Error fetching image for hashing:', error);
// Fallback to URL hashing if image fetch fails
const encoder = new TextEncoder();
const data = encoder.encode(input);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
}
// --- BUTTON CREATION ---
function createHideButton(image) {
const btn = document.createElement('button');
btn.textContent = '✕';
// Use a more robust styling approach
btn.style.setProperty('position', 'fixed', 'important');
btn.style.setProperty('background', 'rgba(0,0,0,0.9)', 'important');
btn.style.setProperty('color', 'white', 'important');
btn.style.setProperty('border', 'none', 'important');
btn.style.setProperty('borderRadius', '3px', 'important');
btn.style.setProperty('padding', '2px 6px', 'important');
btn.style.setProperty('cursor', 'pointer', 'important');
btn.style.setProperty('zIndex', '999999', 'important');
btn.style.setProperty('fontSize', '12px', 'important');
btn.style.setProperty('display', 'none', 'important');
btn.style.setProperty('userSelect', 'none', 'important');
btn.style.setProperty('pointerEvents', 'auto', 'important');
btn.style.setProperty('margin', '0', 'important');
btn.style.setProperty('transform', 'none', 'important');
btn.style.setProperty('float', 'none', 'important');
btn.style.setProperty('clear', 'none', 'important');
btn.style.setProperty('boxShadow', '0 1px 3px rgba(0,0,0,0.5)', 'important');
btn.style.setProperty('fontFamily', 'Arial, sans-serif', 'important');
btn.style.setProperty('fontWeight', 'bold', 'important');
btn.style.setProperty('textAlign', 'center', 'important');
btn.style.setProperty('lineHeight', '1', 'important');
btn.style.setProperty('minWidth', 'auto', 'important');
btn.style.setProperty('minHeight', 'auto', 'important');
btn.style.setProperty('maxWidth', 'none', 'important');
btn.style.setProperty('maxHeight', 'none', 'important');
btn.style.setProperty('width', 'auto', 'important');
btn.style.setProperty('height', 'auto', 'important');
// Store reference to image for positioning
btn._targetImage = image;
btn.addEventListener('click', async (e) => {
// Only prevent default if we're actually going to hide the image
e.stopPropagation();
const checksum = await hashString(image.src);
storeRecord(checksum, image.src);
image.style.display = 'none';
btn.remove(); // Remove from DOM since it's attached to body
});
return btn;
}
// --- DECORATE IMAGE ---
function decorateImage(image) {
console.log('Attempting to decorate image:', image.src);
if (image._hideImageHandled) {
console.log('Image already handled, skipping:', image.src);
return;
}
// Only add hide buttons to images larger than a certain size
const rect = image.getBoundingClientRect();
console.log('Image size check:', image.src, 'size:', rect.width + 'x' + rect.height, 'visible:', rect.width > 0 && rect.height > 0);
if (rect.width < 100 || rect.height < 100) {
console.log('Image too small, skipping:', image.src, 'size:', rect.width + 'x' + rect.height);
return; // Skip small images (likely UI elements, thumbnails, etc.)
}
console.log('Processing image:', image.src);
image._hideImageHandled = true;
const btn = createHideButton(image);
document.body.appendChild(btn);
// Ensure image can receive mouse events
image.style.setProperty('pointer-events', 'auto', 'important');
// Use a more robust hover detection
let isHovering = false;
// Try multiple event types for better compatibility
const showButton = () => {
console.log('Hover event fired for image:', image.src);
isHovering = true;
const rect = image.getBoundingClientRect();
// Debug positioning issues
console.log('Image rect:', rect);
console.log('Image computed style:', getComputedStyle(image));
if (btn._setPosition) {
btn._setPosition(rect);
} else {
// fallback: top-left
btn.style.setProperty('top', (rect.top + 2) + 'px', 'important');
btn.style.setProperty('left', (rect.left + 2) + 'px', 'important');
}
btn.style.setProperty('display', 'block', 'important');
};
const hideButton = () => {
isHovering = false;
setTimeout(() => {
if (!isHovering) {
btn.style.setProperty('display', 'none', 'important');
}
}, 50);
};
// Use passive listeners to avoid interfering with site events
image.addEventListener('mouseenter', showButton, { passive: true });
image.addEventListener('mouseover', showButton, { passive: true });
image.addEventListener('mouseleave', hideButton, { passive: true });
image.addEventListener('mouseout', hideButton, { passive: true });
btn.addEventListener('mouseenter', (e) => {
e.stopPropagation();
isHovering = true;
}, { passive: false });
btn.addEventListener('mouseleave', () => {
isHovering = false;
btn.style.setProperty('display', 'none', 'important');
}, { passive: true });
if (image.parentElement) {
let el = image.parentElement;
while (el) {
el.style.setProperty('pointer-events', 'auto', 'important');
el = el.parentElement;
}
}
}
// --- PROCESS IMAGES WITH BATCHING ---
async function processImagesBatch(images, checksumSet) {
console.log('Processing batch of', images.length, 'images');
const batchSize = 5;
for (let i = 0; i < images.length; i += batchSize) {
const batch = images.slice(i, i + batchSize);
await Promise.all(batch.map(async (img) => {
if (img._hideImageHandled) return;
try {
const checksum = await hashString(img.src);
if (checksumSet.has(checksum)) {
img.style.display = 'none';
img._hideImageHandled = true;
} else {
decorateImage(img);
}
} catch (e) {
console.error("Hash error:", e);
}
}));
}
}
// --- DEBOUNCED OBSERVER ---
let observerTimeout;
const observer = new MutationObserver(() => {
clearTimeout(observerTimeout);
observerTimeout = setTimeout(() => {
const records = getStoredRecords();
const checksumSet = new Set(records.map(r => r.checksum));
const imgs = Array.from(document.querySelectorAll('img'));
processImagesBatch(imgs, checksumSet);
}, 300);
});
// --- MANAGER PANEL ---
function createManagerPanel() {
const toggleBtn = document.createElement('button');
toggleBtn.textContent = '👁 Show Hidden Images';
Object.assign(toggleBtn.style, {
position: 'fixed',
bottom: '10px',
left: '10px',
zIndex: '9999999',
padding: '8px 12px',
background: '#333',
color: '#fff',
border: '2px solid white',
borderRadius: '8px',
fontSize: '14px',
fontWeight: 'bold',
cursor: 'pointer',
boxShadow: '2px 2px 8px rgba(0,0,0,0.3)',
userSelect: 'none',
});
// --- Make the toggle button draggable ---
let isDragging = false;
let dragOffsetX = 0;
let dragOffsetY = 0;
let wasDragged = false;
function positionPanelAboveButton() {
const btnRect = toggleBtn.getBoundingClientRect();
panel.style.left = btnRect.left + 'px';
const gap = 8;
panel.style.bottom = (window.innerHeight - btnRect.top + gap) + 'px';
panel.style.top = 'auto';
}
toggleBtn.addEventListener('mousedown', function(e) {
isDragging = true;
wasDragged = false;
const rect = toggleBtn.getBoundingClientRect();
dragOffsetX = e.clientX - rect.left;
dragOffsetY = e.clientY - rect.top;
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
toggleBtn.style.left = (e.clientX - dragOffsetX) + 'px';
toggleBtn.style.top = (e.clientY - dragOffsetY) + 'px';
toggleBtn.style.bottom = 'auto';
positionPanelAboveButton();
wasDragged = true;
});
document.addEventListener('mouseup', function() {
isDragging = false;
positionPanelAboveButton();
});
// --- End draggable ---
const panel = document.createElement('div');
Object.assign(panel.style, {
position: 'fixed',
bottom: '50px',
left: '10px',
maxHeight: '60vh',
width: '320px',
overflowY: 'auto',
background: '#f9f9f9',
color: '#111',
border: '1px solid #ccc',
padding: '12px',
fontFamily: 'sans-serif',
lineHeight: '1.5',
boxShadow: '2px 2px 10px rgba(0,0,0,0.2)',
zIndex: 999998,
display: 'none',
fontSize: '13px',
userSelect: 'text',
});
function refreshPanel() {
panel.innerHTML = '<strong>Hidden Images</strong><hr>';
const records = getStoredRecords();
if (records.length === 0) {
panel.innerHTML += '<p style="color: #555;">None</p>';
return;
}
for (const rec of records) {
const item = document.createElement('div');
item.style.marginBottom = '12px';
item.style.padding = '6px 0';
item.style.borderBottom = '1px solid #ddd';
item.style.display = 'flex';
item.style.justifyContent = 'space-between';
item.style.alignItems = 'center';
item.style.gap = '10px';
// Filename link
const link = document.createElement('a');
link.href = rec.url;
link.style.fontSize = '13px';
link.style.wordBreak = 'break-word';
link.style.flex = '1';
link.target = '_blank';
link.rel = 'noopener noreferrer';
try {
const urlObj = new URL(rec.url);
const parts = urlObj.pathname.split('/');
const filename = decodeURIComponent(parts[parts.length - 1]);
link.textContent = filename || '(Unnamed Image)';
} catch (e) {
link.textContent = '(Invalid URL)';
}
// Thumbnail
const thumbnail = document.createElement('img');
thumbnail.style.width = '55px';
thumbnail.style.height = '45px';
thumbnail.style.objectFit = 'cover';
thumbnail.style.borderRadius = '4px';
thumbnail.style.border = '1px solid #ddd';
if (rec.thumbnail) {
thumbnail.src = rec.thumbnail;
} else {
thumbnail.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTUiIGhlaWdodD0iNDUiIHZpZXdCb3g9IjAgMCA1NSA0NSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjU1IiBoZWlnaHQ9IjQ1IiBmaWxsPSIjZjBmMGYwIi8+CjxwYXRoIGQ9Ik0yNy41IDIyLjVMMzIuNSAxNy41TDM3LjUgMjIuNUwyNy41IDMyLjVMMTcuNSAyMi41TDIyLjUgMTcuNUwyNy41IDIyLjVaIiBmaWxsPSIjY2NjIi8+Cjwvc3ZnPgo=';
}
// Restore button
const restoreBtn = document.createElement('button');
restoreBtn.textContent = 'Restore';
Object.assign(restoreBtn.style, {
fontSize: '12px',
padding: '4px 8px',
cursor: 'pointer',
background: '#4CAF50',
color: '#fff',
border: 'none',
borderRadius: '4px',
boxShadow: '1px 1px 3px rgba(0,0,0,0.2)',
flexShrink: '0'
});
restoreBtn.addEventListener('click', async () => {
// Remove the record from storage
removeRecord(rec.checksum);
// Find and restore the image on the page
const imgs = Array.from(document.querySelectorAll('img'));
for (const img of imgs) {
try {
const imgChecksum = await hashString(img.src);
if (imgChecksum === rec.checksum) {
// Show the image
img.style.display = '';
img._hideImageHandled = false;
// Re-decorate the image with hide button
decorateImage(img);
break; // Found and restored, no need to continue
}
} catch (e) {
console.error("Hash error during restore:", e);
}
}
// Update the panel
refreshPanel();
});
item.appendChild(link);
item.appendChild(thumbnail);
item.appendChild(restoreBtn);
panel.appendChild(item);
}
}
toggleBtn.addEventListener('click', (e) => {
if (wasDragged) {
// Prevent menu toggle if this click was part of a drag
e.preventDefault();
return;
}
if (panel.style.display === 'none') {
refreshPanel();
// Always position the panel above the button before showing
positionPanelAboveButton();
panel.style.display = 'block';
} else {
panel.style.display = 'none';
}
});
// --- Settings for hide button position ---
const HIDE_BTN_POS_KEY = 'hideBtnPosition';
const defaultHideBtnPos = 'top-left';
function getHideBtnPosition() {
return localStorage.getItem(HIDE_BTN_POS_KEY) || defaultHideBtnPos;
}
function setHideBtnPosition(pos) {
localStorage.setItem(HIDE_BTN_POS_KEY, pos);
}
// --- Helper function to assign position method to button ---
function assignHideBtnPosition(btn) {
// Remove all position props
btn.style.removeProperty('top');
btn.style.removeProperty('left');
btn.style.removeProperty('right');
btn.style.removeProperty('bottom');
// Set position based on user setting
const pos = getHideBtnPosition();
if (pos === 'top-left') {
btn._setPosition = (rect) => {
btn.style.setProperty('top', (rect.top + 2) + 'px', 'important');
btn.style.setProperty('left', (rect.left + 2) + 'px', 'important');
};
} else if (pos === 'top-right') {
btn._setPosition = (rect) => {
btn.style.setProperty('top', (rect.top + 2) + 'px', 'important');
btn.style.setProperty('left', (rect.right - btn.offsetWidth - 2) + 'px', 'important');
};
} else if (pos === 'bottom-left') {
btn._setPosition = (rect) => {
btn.style.setProperty('top', (rect.bottom - btn.offsetHeight - 2) + 'px', 'important');
btn.style.setProperty('left', (rect.left + 2) + 'px', 'important');
};
} else if (pos === 'bottom-right') {
btn._setPosition = (rect) => {
btn.style.setProperty('top', (rect.bottom - btn.offsetHeight - 2) + 'px', 'important');
btn.style.setProperty('left', (rect.right - btn.offsetWidth - 2) + 'px', 'important');
};
}
}
// --- Settings button ---
const settingsBtn = document.createElement('button');
settingsBtn.textContent = '⚙️';
Object.assign(settingsBtn.style, {
marginLeft: '8px',
fontSize: '16px',
cursor: 'pointer',
background: 'transparent',
border: 'none',
color: '#fff',
verticalAlign: 'middle',
});
toggleBtn.appendChild(settingsBtn);
// --- Settings popup ---
const settingsPopup = document.createElement('div');
Object.assign(settingsPopup.style, {
position: 'fixed',
left: '50%',
top: '30%',
transform: 'translate(-50%, 0)',
background: '#fff',
color: '#111',
border: '1px solid #ccc',
borderRadius: '8px',
padding: '18px 24px',
zIndex: 10000000,
boxShadow: '2px 2px 10px rgba(0,0,0,0.2)',
display: 'none',
fontSize: '15px',
});
settingsPopup.innerHTML = `
<div style="margin-bottom: 8px; font-weight: bold;">Hide Button Position</div>
<label><input type="radio" name="hideBtnPos" value="top-left"> Top Left</label><br>
<label><input type="radio" name="hideBtnPos" value="top-right"> Top Right</label><br>
<label><input type="radio" name="hideBtnPos" value="bottom-left"> Bottom Left</label><br>
<label><input type="radio" name="hideBtnPos" value="bottom-right"> Bottom Right</label><br>
`;
document.body.appendChild(settingsPopup);
settingsBtn.addEventListener('click', (e) => {
e.stopPropagation();
// Set checked radio
const pos = getHideBtnPosition();
settingsPopup.querySelectorAll('input[name="hideBtnPos"]').forEach(radio => {
radio.checked = (radio.value === pos);
});
settingsPopup.style.display = 'block';
});
settingsPopup.addEventListener('click', (e) => e.stopPropagation());
settingsPopup.querySelectorAll('input[name="hideBtnPos"]').forEach(radio => {
radio.addEventListener('change', (e) => {
setHideBtnPosition(e.target.value);
settingsPopup.style.display = 'none';
// Update all existing hide buttons
document.querySelectorAll('button').forEach(btn => {
if (btn._targetImage && btn._setPosition) {
// Re-assign the _setPosition method based on new setting
const rect = btn._targetImage.getBoundingClientRect();
// Remove all position props
btn.style.removeProperty('top');
btn.style.removeProperty('left');
btn.style.removeProperty('right');
btn.style.removeProperty('bottom');
// Set new _setPosition
assignHideBtnPosition(btn);
// If the button is visible, reposition it immediately
if (btn.style.display !== 'none') {
btn._setPosition(rect);
}
}
});
});
});
document.addEventListener('click', () => {
settingsPopup.style.display = 'none';
});
// --- Update createHideButton to use user setting ---
const oldCreateHideButton = createHideButton;
createHideButton = function(image) {
const btn = oldCreateHideButton(image);
// Remove all position props
btn.style.removeProperty('top');
btn.style.removeProperty('left');
btn.style.removeProperty('right');
btn.style.removeProperty('bottom');
// Set position based on user setting
assignHideBtnPosition(btn);
return btn;
};
document.body.appendChild(toggleBtn);
document.body.appendChild(panel);
}
// --- THUMBNAIL GENERATION ---
function createThumbnail(imageUrl) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = 55;
canvas.height = 45;
const ctx = canvas.getContext('2d');
// Calculate aspect ratio to fit image properly
const imgAspect = img.width / img.height;
const canvasAspect = 55 / 45;
let drawWidth, drawHeight, offsetX, offsetY;
if (imgAspect > canvasAspect) {
// Image is wider than canvas
drawHeight = 45;
drawWidth = 45 * imgAspect;
offsetX = (55 - drawWidth) / 2;
offsetY = 0;
} else {
// Image is taller than canvas
drawWidth = 55;
drawHeight = 55 / imgAspect;
offsetX = 0;
offsetY = (45 - drawHeight) / 2;
}
ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight);
resolve(canvas.toDataURL('image/jpeg', 0.8));
};
img.onerror = reject;
img.src = imageUrl;
});
}
// --- INIT ---
window.addEventListener('load', () => {
const records = getStoredRecords();
const checksumSet = new Set(records.map(r => r.checksum));
const imgs = Array.from(document.querySelectorAll('img'));
processImagesBatch(imgs, checksumSet);
observer.observe(document.body, { childList: true, subtree: true });
createManagerPanel();
});
})();