-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
548 lines (470 loc) · 18.1 KB
/
Copy pathcontent.js
File metadata and controls
548 lines (470 loc) · 18.1 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
(function() {
let slideshowContainer = null;
let currentImageIndex = 0;
let allImages = [];
let imageLinks = {}; // 图片src到链接的映射
let imageSet = new Set(); // 用于去重
let blacklist = new Set(); // 黑名单
let slideInterval = null;
let slideshowActive = false;
let imageObserver = null; // MutationObserver 实例
let panzoomInstance = null; // Panzoom 实例
let settings = {
interval: 3000,
order: 'sequential'
};
// 页面加载时检查是否需要自动启动幻灯片
checkAutoStart();
// 页面加载时添加全局键盘监听(使用捕获阶段,优先于Vimium等扩展)
document.addEventListener('keydown', handleKeyPress, true);
// 检查是否需要自动启动(从其他页面跳转过来)
function checkAutoStart() {
chrome.storage.local.get(['picflowAutoStart'], function(data) {
if (data.picflowAutoStart) {
// 清除标记
chrome.storage.local.remove(['picflowAutoStart']);
// 延迟启动,等待页面加载
setTimeout(() => {
chrome.storage.sync.get(['interval', 'order'], function(syncData) {
settings.interval = (syncData.interval || 3) * 1000;
settings.order = syncData.order || 'sequential';
startSlideshow();
});
}, 1500);
}
});
}
// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.action) {
case 'START_SLIDESHOW':
Object.assign(settings, request.settings);
startSlideshow();
sendResponse({status: 'started'});
break;
case 'STOP_SLIDESHOW':
stopSlideshow();
sendResponse({status: 'stopped'});
break;
case 'UPDATE_SETTINGS':
Object.assign(settings, request.settings);
restartInterval();
sendResponse({status: 'updated'});
break;
}
return true;
});
// 检查图片是否有效(足够大且不在黑名单中)
function isValidImage(img) {
return img.width > 50 && img.height > 50 && img.src && !imageSet.has(img.src) && !blacklist.has(img.src);
}
// 检查URL是否是图片资源
function isImageUrl(url) {
if (!url) return false;
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico'];
const lowerUrl = url.toLowerCase().split('?')[0]; // 去掉查询参数
return imageExtensions.some(ext => lowerUrl.endsWith(ext));
}
// 添加新图片到幻灯片
function addImageToSlideshow(src, link = null) {
if (!imageSet.has(src) && !blacklist.has(src)) {
imageSet.add(src);
allImages.push(src);
if (link) {
imageLinks[src] = link;
}
updateCounter();
}
}
// 收集页面所有图片
function collectImages() {
document.querySelectorAll('img').forEach(img => {
if (isValidImage(img)) {
// 查找图片的父级链接
const parentLink = img.closest('a');
const link = parentLink ? parentLink.href : null;
addImageToSlideshow(img.src, link);
}
});
}
// 开始监听新加载的图片
function startImageObserver() {
if (imageObserver) return;
imageObserver = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
// 检查新添加的节点
mutation.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
// 如果是图片元素
if (node.tagName === 'IMG') {
checkAndAddImage(node);
}
// 如果是其他元素,检查其内部的图片
node.querySelectorAll && node.querySelectorAll('img').forEach(img => {
checkAndAddImage(img);
});
}
});
// 检查属性变化(src变化)
if (mutation.type === 'attributes' &&
mutation.attributeName === 'src' &&
mutation.target.tagName === 'IMG') {
checkAndAddImage(mutation.target);
}
});
});
// 监听整个文档的变化
imageObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['src']
});
}
// 检查并添加图片
function checkAndAddImage(img) {
if (!slideshowActive) return;
// 如果图片还没加载完,等待加载
if (!img.complete) {
img.addEventListener('load', function onLoad() {
img.removeEventListener('load', onLoad);
if (isValidImage(img)) {
const parentLink = img.closest('a');
const link = parentLink ? parentLink.href : null;
addImageToSlideshow(img.src, link);
}
});
} else if (isValidImage(img)) {
const parentLink = img.closest('a');
const link = parentLink ? parentLink.href : null;
addImageToSlideshow(img.src, link);
}
}
// 停止监听
function stopImageObserver() {
if (imageObserver) {
imageObserver.disconnect();
imageObserver = null;
}
}
// 跳转到当前图片的链接页面
function followCurrentImageLink() {
if (allImages.length === 0) return;
const currentSrc = allImages[currentImageIndex];
const link = imageLinks[currentSrc];
if (!link) return; // 没有链接
if (link === window.location.href) return; // 同一页面
if (isImageUrl(link)) return; // 是图片资源,不跳转
// 设置标记,让新页面自动启动幻灯片
chrome.storage.local.set({ picflowAutoStart: true }, function() {
window.location.href = link;
});
}
function startSlideshow() {
// 获取黑名单
chrome.storage.local.get(['picflowBlacklist'], function(data) {
blacklist = new Set(data.picflowBlacklist || []);
// 重置状态
allImages = [];
imageLinks = {};
imageSet.clear();
// 收集页面所有图片
collectImages();
if (allImages.length === 0) {
return;
}
slideshowActive = true;
currentImageIndex = 0;
createSlideshowContainer();
showCurrentImage();
startAutoPlay();
// 开始监听新加载的图片
startImageObserver();
});
}
function stopSlideshow() {
// 停止监听新图片
stopImageObserver();
// 销毁 Panzoom 实例
if (panzoomInstance) {
panzoomInstance.dispose();
panzoomInstance = null;
}
if (slideshowContainer) {
slideshowContainer.remove();
slideshowContainer = null;
}
// 恢复页面原有内容
document.body.style.overflow = '';
Array.from(document.body.children).forEach(child => {
if (child.dataset.slideshowHidden !== undefined) {
child.style.display = child.dataset.slideshowHidden || '';
delete child.dataset.slideshowHidden;
}
});
stopAutoPlay();
slideshowActive = false;
// 清空图片集合
allImages = [];
imageLinks = {};
imageSet.clear();
}
function createSlideshowContainer() {
// 如果容器已存在,先移除
if (slideshowContainer) slideshowContainer.remove();
// 隐藏页面原有内容
document.body.style.overflow = 'hidden';
Array.from(document.body.children).forEach(child => {
if (child.id !== 'chrome-slideshow-container') {
child.dataset.slideshowHidden = child.style.display;
child.style.display = 'none';
}
});
// 创建容器
slideshowContainer = document.createElement('div');
slideshowContainer.id = 'chrome-slideshow-container';
// 创建图片显示区域
const imgDisplay = document.createElement('div');
imgDisplay.className = 'slideshow-display';
const imgElement = document.createElement('img');
imgElement.id = 'slideshow-current-img';
// 双击放大/缩小功能
imgElement.addEventListener('dblclick', function(e) {
e.preventDefault();
e.stopPropagation();
if (!panzoomInstance) return;
stopAutoPlay();
const transform = panzoomInstance.getTransform();
// 如果已经放大或移动了,恢复原状
if (transform.scale > 1.05 || transform.scale < 0.95) {
// 恢复到原始大小,以点击位置为锚点
panzoomInstance.zoomAbs(e.clientX, e.clientY, 1);
} else {
// 原地放大,以点击位置为锚点(点击位置的内容保持不动)
panzoomInstance.zoomAbs(e.clientX, e.clientY, 1.5);
}
});
imgDisplay.appendChild(imgElement);
// 创建计数器(右上角显示)
const counter = document.createElement('div');
counter.id = 'slideshow-counter';
counter.textContent = `1 / ${allImages.length}`;
// 组装容器
slideshowContainer.appendChild(imgDisplay);
slideshowContainer.appendChild(counter);
document.body.appendChild(slideshowContainer);
}
function showCurrentImage() {
if (!slideshowContainer || allImages.length === 0) return;
// 切换图片前销毁旧的 panzoom 实例
if (panzoomInstance) {
panzoomInstance.dispose();
panzoomInstance = null;
}
// 确保索引在有效范围内
if (currentImageIndex >= allImages.length) {
currentImageIndex = allImages.length - 1;
}
if (currentImageIndex < 0) {
currentImageIndex = 0;
}
const imgElement = document.getElementById('slideshow-current-img');
// 重置可能残留的 transform 和 panzoom 状态
imgElement.classList.remove('panzoom-active');
imgElement.style.transform = '';
imgElement.style.width = '';
imgElement.style.height = '';
// 图片加载完成后初始化 panzoom
imgElement.onload = function() {
initPanzoom(imgElement);
};
imgElement.src = allImages[currentImageIndex];
updateCounter();
}
// 初始化 panzoom 实例
function initPanzoom(imgElement) {
if (panzoomInstance) {
panzoomInstance.dispose();
panzoomInstance = null;
}
if (typeof panzoom !== 'function') return;
const container = imgElement.parentElement;
const containerRect = container.getBoundingClientRect();
// 使用图片原始尺寸计算适应屏幕的尺寸
const naturalWidth = imgElement.naturalWidth;
const naturalHeight = imgElement.naturalHeight;
const containerWidth = containerRect.width;
const containerHeight = containerRect.height;
// 计算缩放比例,使图片适应容器
const scaleX = containerWidth / naturalWidth;
const scaleY = containerHeight / naturalHeight;
const scale = Math.min(scaleX, scaleY, 1); // 不超过原始尺寸
const fitWidth = naturalWidth * scale;
const fitHeight = naturalHeight * scale;
// 计算居中位置
const initialX = (containerWidth - fitWidth) / 2;
const initialY = (containerHeight - fitHeight) / 2;
// 切换到 panzoom 模式,并锁定图片尺寸
imgElement.classList.add('panzoom-active');
imgElement.style.width = fitWidth + 'px';
imgElement.style.height = fitHeight + 'px';
// 先创建 panzoom 实例(此时图片在 0,0 位置)
panzoomInstance = panzoom(imgElement, {
maxZoom: 10,
minZoom: 0.5,
bounds: false,
boundsPadding: 0.1,
smoothScroll: false
});
// 然后用 moveTo 设置居中位置
panzoomInstance.moveTo(initialX, initialY);
// 监听缩放事件,滚轮缩放时暂停播放
panzoomInstance.on('zoom', function() {
stopAutoPlay();
});
}
function showNextImage() {
if (allImages.length === 0) return;
if (settings.order === 'random') {
currentImageIndex = Math.floor(Math.random() * allImages.length);
} else {
currentImageIndex = (currentImageIndex + 1) % allImages.length;
}
showCurrentImage();
}
function showPreviousImage() {
if (allImages.length === 0) return;
if (settings.order === 'random') {
currentImageIndex = Math.floor(Math.random() * allImages.length);
} else {
currentImageIndex = (currentImageIndex - 1 + allImages.length) % allImages.length;
}
showCurrentImage();
}
function startAutoPlay() {
stopAutoPlay();
slideInterval = setInterval(showNextImage, settings.interval);
updateCounter();
}
function stopAutoPlay() {
if (slideInterval) {
clearInterval(slideInterval);
slideInterval = null;
}
updateCounter();
}
function togglePlayPause() {
if (slideInterval) {
stopAutoPlay();
} else {
startAutoPlay();
}
}
function restartInterval() {
if (slideInterval) {
stopAutoPlay();
startAutoPlay();
}
}
function updateCounter() {
const counter = document.getElementById('slideshow-counter');
if (counter) {
const status = slideInterval ? '▶' : '⏸';
counter.textContent = `${status} ${currentImageIndex + 1} / ${allImages.length}`;
}
}
function saveCurrentImage() {
if (allImages.length === 0) return;
const currentSrc = allImages[currentImageIndex];
const filename = `picflow_${Date.now()}.jpg`;
// 发送消息给 background script 下载图片
chrome.runtime.sendMessage({
action: 'DOWNLOAD_IMAGE',
url: currentSrc,
filename: filename
}, function(response) {
if (response && response.success) {
// 下载请求成功
console.log('Download started');
} else {
console.error('Download failed:', response ? response.error : 'Unknown error');
}
});
}
function handleKeyPress(event) {
// 忽略输入框中的按键
if (event.target.tagName === 'INPUT' ||
event.target.tagName === 'TEXTAREA' ||
event.target.isContentEditable) {
return;
}
// 幻灯片未激活时,只响应A键
if (!slideshowActive) {
if (event.key === 'a' || event.key === 'A') {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
// 从存储中获取设置
chrome.storage.sync.get(['interval', 'order'], function(data) {
settings.interval = (data.interval || 3) * 1000;
settings.order = data.order || 'sequential';
startSlideshow();
});
}
return;
}
// 幻灯片激活时,阻止所有快捷键传播给其他扩展
event.stopPropagation();
event.stopImmediatePropagation();
switch(event.key) {
case 'Escape':
event.preventDefault();
stopSlideshow();
break;
case 'ArrowLeft':
event.preventDefault();
showPreviousImage();
break;
case 'ArrowRight':
event.preventDefault();
showNextImage();
break;
case 's':
case 'S':
event.preventDefault();
saveCurrentImage();
break;
case ' ': // 空格键切换播放/暂停
event.preventDefault();
togglePlayPause();
break;
case 'Enter': // 回车键跳转到图片链接页面
event.preventDefault();
followCurrentImageLink();
break;
case 'Delete':
case 'Backspace': // 支持 Delete 和 Backspace
event.preventDefault();
if (allImages.length > 0) {
const currentSrc = allImages[currentImageIndex];
blacklist.add(currentSrc);
// 保存黑名单
chrome.storage.local.set({ picflowBlacklist: Array.from(blacklist) });
// 从当前列表中移除
allImages.splice(currentImageIndex, 1);
imageSet.delete(currentSrc);
// 不必删除 imageLinks 中的条目,它不影响逻辑
if (allImages.length === 0) {
stopSlideshow();
} else {
// 修正索引
if (currentImageIndex >= allImages.length) {
currentImageIndex = allImages.length - 1;
}
showCurrentImage();
}
}
break;
}
}
})();