// ==UserScript== // @name 图片隐藏 // @namespace http://tampermonkey.net/ // @version 1.3 // @description 单张或者全局图片隐藏与显示 // @match *://*/* // @author eternal5130 // @license MIT // @grant GM_setValue // @grant GM_getValue // @grant GM_registerMenuCommand // @grant GM_addStyle // @downloadURL https://update.greasyfork.icu/scripts/519838/%E5%9B%BE%E7%89%87%E9%9A%90%E8%97%8F.user.js // @updateURL https://update.greasyfork.icu/scripts/519838/%E5%9B%BE%E7%89%87%E9%9A%90%E8%97%8F.meta.js // ==/UserScript== (function() { 'use strict'; const STORAGE_KEY_SHORTCUT = 'imageHiderShortcut_v2'; const STORAGE_KEY_GLOBAL_HIDE = 'imageHiderGlobalHideState_v2'; const CSS_CLASS_HIDDEN = 'image-hider--hidden'; const CSS_CLASS_OVERLAY = 'image-hider--overlay'; const CSS_MODAL_ID = 'image-hider-modal-styles'; const DEFAULT_SHORTCUT = { single: { keys: ['MouseMiddle'] }, global: { keys: ['AltLeft', 'KeyH'] } }; const DEBOUNCE_DELAY = 250; const THROTTLE_DELAY = 50; const imageStates = new Map(); const currentPressedKeys = new Set(); let currentHoverTarget = null; let configModal = null; let globalImageCounter = 0; let mutationObserver = null; const KEY_NAME_MAP = { 'AltLeft': 'Alt (左)', 'AltRight': 'Alt (右)', 'ControlLeft': 'Ctrl (左)', 'ControlRight': 'Ctrl (右)', 'ShiftLeft': 'Shift (左)', 'ShiftRight': 'Shift (右)', 'MetaLeft': 'Meta (左)', 'MetaRight': 'Meta (右)', 'MouseLeft': '鼠标左键', 'MouseMiddle': '鼠标中键', 'MouseRight': '鼠标右键', 'KeyA': 'A', 'KeyB': 'B', 'KeyC': 'C', 'KeyD': 'D', 'KeyE': 'E', 'KeyF': 'F', 'KeyG': 'G', 'KeyH': 'H', 'KeyI': 'I', 'KeyJ': 'J', 'KeyK': 'K', 'KeyL': 'L', 'KeyM': 'M', 'KeyN': 'N', 'KeyO': 'O', 'KeyP': 'P', 'KeyQ': 'Q', 'KeyR': 'R', 'KeyS': 'S', 'KeyT': 'T', 'KeyU': 'U', 'KeyV': 'V', 'KeyW': 'W', 'KeyX': 'X', 'KeyY': 'Y', 'KeyZ': 'Z', 'Digit0': '0', 'Digit1': '1', 'Digit2': '2', 'Digit3': '3', 'Digit4': '4', 'Digit5': '5', 'Digit6': '6', 'Digit7': '7', 'Digit8': '8', 'Digit9': '9' }; function getKeyDisplayName(code) { return KEY_NAME_MAP[code] || code; } function throttle(func, limit) { let inThrottle; return function(...args) { const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } } } function getShortcutConfig() { try { const savedConfig = GM_getValue(STORAGE_KEY_SHORTCUT); const parsed = savedConfig ? JSON.parse(savedConfig) : {}; return { single: { keys: parsed?.single?.keys || DEFAULT_SHORTCUT.single.keys }, global: { keys: parsed?.global?.keys || DEFAULT_SHORTCUT.global.keys } }; } catch (error) { // console.error('Image Hider: Failed to get shortcut config, using defaults.', error); return { ...DEFAULT_SHORTCUT }; } } function saveShortcutConfig(config) { try { GM_setValue(STORAGE_KEY_SHORTCUT, JSON.stringify(config)); } catch (error) { // console.error('Image Hider: Failed to save shortcut config.', error); alert('保存配置时出错,请重试'); } } function getGlobalHideState() { return GM_getValue(STORAGE_KEY_GLOBAL_HIDE, false); } function setGlobalHideState(state) { GM_setValue(STORAGE_KEY_GLOBAL_HIDE, state); } class ImageState { constructor(imgElement) { this.element = imgElement; this.isHidden = false; this.overlay = null; this.observers = new Set(); this.lastToggleTime = 0; this.userManuallyShown = false; this.isProcessing = false; } cleanup() { this.observers.forEach(observer => observer.disconnect()); this.observers.clear(); if (this.overlay) { this.overlay.cleanup?.(); this.overlay.remove(); this.overlay = null; } } } function ensureImageState(imgElement) { if (!imgElement || !(imgElement instanceof HTMLImageElement)) return null; let imageId = imgElement.dataset.imageId; if (!imageId) { imageId = `img_hider_${++globalImageCounter}`; imgElement.dataset.imageId = imageId; } if (!imageStates.has(imageId)) { imageStates.set(imageId, new ImageState(imgElement)); } return imageStates.get(imageId); } function createOverlay(imgElement, state) { if (!imgElement?.parentNode || !state) return null; const overlay = document.createElement('div'); overlay.className = CSS_CLASS_OVERLAY; overlay.dataset.linkedImageId = imgElement.dataset.imageId; const updatePosition = throttle(() => { if (!imgElement || !imgElement.parentNode || !document.body.contains(imgElement)) { state.cleanup(); imageStates.delete(imgElement.dataset.imageId); return; } const rect = imgElement.getBoundingClientRect(); if (rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth) { Object.assign(overlay.style, { left: `${rect.left + window.scrollX}px`, top: `${rect.top + window.scrollY}px`, width: `${rect.width}px`, height: `${rect.height}px`, }); if (!document.body.contains(overlay)) { document.body.appendChild(overlay); } } }, THROTTLE_DELAY); requestAnimationFrame(updatePosition); const intersectionObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { requestAnimationFrame(updatePosition); } }); }, { threshold: 0.1 }); intersectionObserver.observe(imgElement); state.observers.add(intersectionObserver); const resizeObserver = new ResizeObserver(() => requestAnimationFrame(updatePosition)); resizeObserver.observe(imgElement); state.observers.add(resizeObserver); const scrollHandler = () => requestAnimationFrame(updatePosition); window.addEventListener('scroll', scrollHandler, { passive: true, capture: true }); overlay.addEventListener('mouseover', () => { currentHoverTarget = state.element; }); overlay.addEventListener('mouseout', () => { currentHoverTarget = null; }); overlay.addEventListener('mousedown', (e) => { if (e.button === 1) { e.preventDefault(); const shortcutConfig = getShortcutConfig(); if (shortcutConfig.single.keys.includes('MouseMiddle') && currentHoverTarget === state.element) { currentPressedKeys.add('MouseMiddle'); checkShortcut(); currentPressedKeys.delete('MouseMiddle'); } else { toggleImageVisibility(state.element); } } }); overlay.cleanup = () => { window.removeEventListener('scroll', scrollHandler, { capture: true }); }; document.body.appendChild(overlay); return overlay; } function toggleImageVisibility(imgElement, forceHide = null, isInitialAutoHide = false) { const state = ensureImageState(imgElement); if (!state || !state.element?.parentNode || !document.body.contains(state.element)) { if (state && imgElement?.dataset?.imageId) { state.cleanup(); imageStates.delete(imgElement.dataset.imageId); } return; } const currentTime = Date.now(); if (state.isProcessing || (currentTime - state.lastToggleTime < DEBOUNCE_DELAY)) { return; } state.isProcessing = true; state.lastToggleTime = currentTime; if (isInitialAutoHide && state.userManuallyShown) { state.isProcessing = false; return; } const shouldHide = (forceHide !== null) ? forceHide : !state.isHidden; if (!isInitialAutoHide && !shouldHide) { state.userManuallyShown = true; } else if (!isInitialAutoHide && shouldHide) { state.userManuallyShown = false; } try { if (shouldHide) { state.element.classList.add(CSS_CLASS_HIDDEN); if (!state.overlay) { state.overlay = createOverlay(state.element, state); } if (state.overlay && !document.body.contains(state.overlay)) { document.body.appendChild(state.overlay); } } else { state.element.classList.remove(CSS_CLASS_HIDDEN); if (state.overlay) { state.cleanup(); } } state.isHidden = shouldHide; } catch (error) { // console.error('Image Hider: Error toggling visibility for', state.element, error); } finally { setTimeout(() => { state.isProcessing = false; }, DEBOUNCE_DELAY + 50); } } function toggleAllImages() { const images = document.getElementsByTagName('img'); const shouldHide = !getGlobalHideState(); setGlobalHideState(shouldHide); requestAnimationFrame(() => { Array.from(images).forEach(img => { ensureImageState(img); toggleImageVisibility(img, shouldHide, false); }); if (shouldHide) { imageStates.forEach(state => state.userManuallyShown = false); } }); } function processImages(imageList, applyGlobalState) { Array.from(imageList).forEach(img => { const state = ensureImageState(img); if (state && applyGlobalState) { if (!state.isHidden) { img.classList.add(CSS_CLASS_HIDDEN); toggleImageVisibility(img, true, true); } } else if (state && !applyGlobalState && state.isHidden) { toggleImageVisibility(img, false, false); } }); } function initAutoHideAndObserver() { const globalShouldHide = getGlobalHideState(); processImages(document.getElementsByTagName('img'), globalShouldHide); if (mutationObserver) mutationObserver.disconnect(); mutationObserver = new MutationObserver((mutations) => { const currentGlobalHideState = getGlobalHideState(); mutations.forEach(mutation => { if (mutation.addedNodes.length) { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { const newImages = []; if (node.tagName === 'IMG') { newImages.push(node); } else if (node.querySelectorAll) { newImages.push(...node.querySelectorAll('img')); } if (newImages.length > 0) { processImages(newImages, currentGlobalHideState); } } }); } if (mutation.removedNodes.length) { mutation.removedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { const removedImages = []; if (node.tagName === 'IMG' && node.dataset.imageId) { removedImages.push(node); } else if (node.querySelectorAll) { removedImages.push(...node.querySelectorAll('img[data-image-id]')); } removedImages.forEach(img => { const imageId = img.dataset.imageId; if (imageId && imageStates.has(imageId)) { const state = imageStates.get(imageId); state.cleanup(); imageStates.delete(imageId); } }); } }); } if (mutation.type === 'attributes' && mutation.attributeName === 'src') { const imgElement = mutation.target; if (imgElement.tagName === 'IMG' && getGlobalHideState()) { const state = ensureImageState(imgElement); if (state && !state.isHidden) { imgElement.classList.add(CSS_CLASS_HIDDEN); toggleImageVisibility(imgElement, true, true); } } } }); }); mutationObserver.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] }); } function handleKeyDown(event) { const targetTagName = event.target.tagName.toLowerCase(); if (['input', 'textarea', 'select'].includes(targetTagName) || event.target.isContentEditable) { return; } currentPressedKeys.add(event.code); checkShortcut(); } function handleKeyUp(event) { currentPressedKeys.delete(event.code); } function handleMouseDown(event) { if (event.button === 1) { const shortcutConfig = getShortcutConfig(); if (shortcutConfig.single.keys.includes('MouseMiddle') && currentHoverTarget) { event.preventDefault(); } currentPressedKeys.add('MouseMiddle'); checkShortcut(); } } function handleMouseUp(event) { if (event.button === 1) { currentPressedKeys.delete('MouseMiddle'); } } function handleMouseOver(event) { if (event.target.tagName === 'IMG') { currentHoverTarget = event.target; ensureImageState(currentHoverTarget); } else if (event.target.classList?.contains(CSS_CLASS_OVERLAY)) { const linkedImageId = event.target.dataset.linkedImageId; const state = linkedImageId ? imageStates.get(linkedImageId) : null; if (state?.element) { currentHoverTarget = state.element; } } } function handleMouseOut(event) { if (event.target === currentHoverTarget || event.target.classList?.contains(CSS_CLASS_OVERLAY)) { if (!event.relatedTarget || (event.relatedTarget !== currentHoverTarget && !event.relatedTarget.classList?.contains(CSS_CLASS_OVERLAY))) { currentHoverTarget = null; } } } function resetStateOnUnload() { currentPressedKeys.clear(); currentHoverTarget = null; if (mutationObserver) { mutationObserver.disconnect(); mutationObserver = null; } } function checkShortcut() { const shortcutConfig = getShortcutConfig(); const isExactMatch = (keys) => { return keys.length === currentPressedKeys.size && keys.every(key => currentPressedKeys.has(key)); } if (currentHoverTarget && isExactMatch(shortcutConfig.single.keys)) { toggleImageVisibility(currentHoverTarget); } if (isExactMatch(shortcutConfig.global.keys)) { toggleAllImages(); currentPressedKeys.clear(); } } function createConfigModal() { if (configModal) return; injectGlobalStyles(); configModal = document.createElement('div'); configModal.className = 'image-hider-modal'; configModal.id = 'image-hider-config-modal'; const currentConfig = getShortcutConfig(); let tempSingleKeys = new Set(currentConfig.single.keys); let tempGlobalKeys = new Set(currentConfig.global.keys); let isRecording = false; let currentRecordingType = null; let recordingCleanup = null; function formatKeys(keys) { return Array.from(keys).map(getKeyDisplayName).join(' + ') || '无'; } function renderModalContent() { const singleShortcutDisplay = formatKeys(tempSingleKeys); const globalShortcutDisplay = formatKeys(tempGlobalKeys); configModal.innerHTML = `