Nijie Popup Preview

Show a popup preview next to the hovered thumbnail, switch images with the mouse wheel over the thumbnail, loop images, and remember scroll position.

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey, Greasemonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Nijie Popup Preview
// @namespace    http://tampermonkey.net/
// @version      2.2
// @description  Show a popup preview next to the hovered thumbnail, switch images with the mouse wheel over the thumbnail, loop images, and remember scroll position.
// @author       (´・ω・`)
// @license      MIT
// @match        *://nijie.info/*
// @icon         https://nijie.info/icon/favicon.ico?1786790486
// @grant        none
// ==/UserScript==

/*
MIT License

Copyright (c) 2026 (´・ω・`)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

(function() {
    'use strict';

    // --- Internationalization (i18n) setup ---
    const isJapanese = (navigator.language || navigator.userLanguage || '').toLowerCase().startsWith('ja');
    const i18n = {
        loading: isJapanese ? '読み込み中...' : 'Loading...',
        error: isJapanese ? 'エラーが発生しました' : 'An error occurred',
        notFound: isJapanese ? '画像が見つかりません' : 'No images found',
        wheel: isJapanese ? '(ホイールで切替)' : '(Wheel to switch)'
    };

    // --- Create popup element and set styles ---
    const popup = document.createElement('div');
    popup.id = 'nijie-hover-popup';
    Object.assign(popup.style, {
        position: 'fixed',
        backgroundColor: 'rgba(0, 0, 0, 0.85)',
        border: '2px solid #555',
        borderRadius: '8px',
        padding: '10px',
        zIndex: '999999',
        display: 'none',
        flexDirection: 'column',
        alignItems: 'center',
        boxShadow: '0 4px 15px rgba(0,0,0,0.6)',
        transition: 'opacity 0.15s ease-in-out',
        opacity: '0',
        boxSizing: 'border-box',
        pointerEvents: 'none'
    });

    const counterEl = document.createElement('div');
    Object.assign(counterEl.style, {
        color: '#fff',
        marginBottom: '8px',
        fontSize: '14px',
        fontWeight: 'bold',
        fontFamily: 'sans-serif',
        textShadow: '1px 1px 2px #000'
    });

    const imgEl = document.createElement('img');
    Object.assign(imgEl.style, {
        maxWidth: 'calc(100vw - 40px)', 
        maxHeight: 'calc(100vh - 80px)',
        objectFit: 'contain',
        display: 'none',
        borderRadius: '4px'
    });

    popup.appendChild(counterEl);
    popup.appendChild(imgEl);
    document.body.appendChild(popup);

    // --- State management variables ---
    let currentImages = [];
    let currentIndex = 0;
    let currentPopupId = null; 
    let activeThumbnail = null;
    const cache = {};
    const indexCache = {};

    // --- Core functions ---

    function renderImage() {
        imgEl.src = currentImages[currentIndex];
        imgEl.style.display = 'block';
        if (currentImages.length > 1) {
            counterEl.textContent = `${currentIndex + 1} / ${currentImages.length} ${i18n.wheel}`;
            counterEl.style.display = 'block';
        } else {
            counterEl.style.display = 'none';
        }
        updatePopupPosition();
    }

    function updatePopupPosition() {
        if (popup.style.display === 'none' || !activeThumbnail) return;
        
        const thumbRect = activeThumbnail.getBoundingClientRect();
        const pWidth = popup.offsetWidth;
        const pHeight = popup.offsetHeight;
        
        const gap = 15;
        let left = thumbRect.right + gap;
        let top = thumbRect.top;

        if (left + pWidth > window.innerWidth - 10) {
            left = thumbRect.left - pWidth - gap;
        }
        
        if (left < 10) {
            left = 10;
        }

        if (top + pHeight > window.innerHeight - 10) {
            top = window.innerHeight - pHeight - 10;
        }
        
        if (top < 10) top = 10;

        popup.style.left = left + 'px';
        popup.style.top = top + 'px';
        popup.style.right = 'auto';
        popup.style.bottom = 'auto';
    }

    imgEl.addEventListener('load', () => {
        updatePopupPosition();
    });

    async function showPopup(id, thumbElement) {
        currentPopupId = id;
        activeThumbnail = thumbElement;
        
        counterEl.textContent = i18n.loading;
        counterEl.style.display = 'block';
        imgEl.src = '';
        imgEl.style.display = 'none';

        popup.style.display = 'flex';
        updatePopupPosition();
        setTimeout(() => { popup.style.opacity = '1'; }, 10);

        if (!cache[id]) {
            try {
                const res = await fetch(`https://nijie.info/view_popup.php?id=${id}`);
                const text = await res.text();
                const doc = new DOMParser().parseFromString(text, 'text/html');
                
                const validSrcs = [];
                const targetImages = doc.querySelectorAll('#img_window div[id^="diff_"] img');
                
                targetImages.forEach(img => {
                    const src = img.getAttribute('data-src') || img.getAttribute('src');
                    if (src) {
                        const absoluteUrl = new URL(src, window.location.origin).href;
                        validSrcs.push(absoluteUrl);
                    }
                });
                
                cache[id] = [...new Set(validSrcs)];
            } catch(e) {
                if (currentPopupId === id) {
                    counterEl.textContent = i18n.error;
                    updatePopupPosition();
                }
                return;
            }
        }

        if (currentPopupId !== id) return;

        currentImages = cache[id];
        
        currentIndex = indexCache[id] !== undefined ? indexCache[id] : 0;
        if (currentIndex >= currentImages.length) {
            currentIndex = 0;
        }
        
        if (currentImages.length > 0) {
            renderImage();
        } else {
            counterEl.textContent = i18n.notFound;
            updatePopupPosition();
        }
    }

    function hidePopup() {
        popup.style.opacity = '0';
        setTimeout(() => {
            if (popup.style.opacity === '0') {
                popup.style.display = 'none';
                currentPopupId = null;
                activeThumbnail = null;
            }
        }, 150);
    }

    // --- Event Listeners ---
    
    document.addEventListener('mouseover', (e) => {
        const a = e.target.closest('a[href*="view.php"]');
        if (a) {
            const url = new URL(a.href, window.location.origin);
            const id = url.searchParams.get('id');
            if (id && currentPopupId !== id) {
                showPopup(id, a);
            }
        }
    });

    document.addEventListener('mouseout', (e) => {
        const a = e.target.closest('a[href*="view.php"]');
        if (a && a === activeThumbnail) {
            if (e.relatedTarget && a.contains(e.relatedTarget)) {
                return;
            }
            if (currentPopupId) {
                indexCache[currentPopupId] = currentIndex;
            }
            hidePopup();
        }
    });

    document.addEventListener('wheel', (e) => {
        if (!activeThumbnail) return;
        
        const targetA = e.target.closest('a[href*="view.php"]');
        if (!targetA || targetA !== activeThumbnail) return;
        
        if (currentImages.length <= 1) return;
        
        e.preventDefault();
        
        if (e.deltaY > 0) {
            currentIndex = (currentIndex + 1) % currentImages.length;
            renderImage();
        } else if (e.deltaY < 0) {
            currentIndex = (currentIndex - 1 + currentImages.length) % currentImages.length;
            renderImage();
        }
        
        if (currentPopupId) {
            indexCache[currentPopupId] = currentIndex;
        }
    }, { passive: false });

})();