preview at hover
// ==UserScript==
// @name Rule34Video - Thumbnail Preview
// @namespace r34video
// @version 9.5.0
// @description preview at hover
// @match https://rule34video.com/*
// @grant none
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
const HOVER_DELAY = 500;
const ZOOM_MAX_WIDTH = 850;
const ZOOM_RATIO = 16 / 9;
const ZOOM_GAP = 10;
const AUDIO_STORAGE_KEY =
'r34_zoom_audio_unlocked';
let audioUnlocked = false;
try {
audioUnlocked =
localStorage.getItem(
AUDIO_STORAGE_KEY
) === '1';
} catch (e) {
audioUnlocked = false;
}
let zoomBox = null;
let zoomVideo = null;
let zoomTitle = null;
let zoomProgress = null;
let zoomTime = null;
let zoomPlay = null;
let zoomMute = null;
let audioOverlay = null;
let currentCard = null;
let currentFullUrl = '';
let hideTimer = null;
let zoomOpen = false;
const fullVideoCache = new Map();
const fullVideoLoading = new Map();
const hoverTimers =
new WeakMap();
/*
* =========================================================
* STYLE
* =========================================================
*/
const style =
document.createElement('style');
style.textContent = `
#r34v802-zoom {
position: fixed;
z-index: 2147483647;
width: ${ZOOM_MAX_WIDTH}px;
height: ${ZOOM_MAX_WIDTH / ZOOM_RATIO}px;
background: #000;
border-radius: 8px;
overflow: hidden;
box-shadow:
0 12px 40px rgba(0,0,0,.65);
display: none;
user-select: none;
}
#r34v802-video {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
object-fit: contain;
background: #000;
cursor: pointer;
}
#r34v802-title {
position: absolute;
left: 0;
right: 0;
top: 0;
z-index: 20;
padding:
9px
12px
24px;
color: #fff;
font-size: 13px;
line-height: 1.3;
background:
linear-gradient(
to bottom,
rgba(0,0,0,.72),
rgba(0,0,0,0)
);
pointer-events: none;
}
#r34v802-controls {
position: absolute;
left: 0;
right: 0;
bottom: 0;
z-index: 20;
display: flex;
align-items: center;
gap: 7px;
padding: 8px;
color: #fff;
background:
linear-gradient(
to top,
rgba(0,0,0,.78),
rgba(0,0,0,0)
);
}
#r34v802-controls button {
border: 0;
background:
rgba(0,0,0,.5);
color: #fff;
width: 30px;
height: 28px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
padding: 0;
}
#r34v802-controls button:hover {
background:
rgba(255,255,255,.2);
}
#r34v802-progress {
flex: 1;
min-width: 50px;
cursor: pointer;
}
#r34v802-time {
min-width: 75px;
text-align: right;
font-size: 11px;
font-variant-numeric:
tabular-nums;
}
#r34v802-audio:hover {
background:
rgba(30,30,30,.94);
}
/*
* =====================================================
* MAŁE VIDEO NA KAFELKACH
* =====================================================
*/
.r34v802-preview-wrap {
position: relative !important;
overflow: hidden !important;
}
.r34v802-card-video {
position: absolute !important;
left: 0 !important;
top: 0 !important;
width: 100% !important;
height: 100% !important;
object-fit: cover !important;
z-index: 2 !important;
display: block !important;
background: #000 !important;
opacity: 0;
transition:
opacity .12s ease;
pointer-events: none !important;
}
.r34v802-card-video.r34v802-ready {
opacity: 1;
}
`;
document.head.appendChild(style);
/*
* =========================================================
* SAFE PLAY
* =========================================================
*/
function safePlay(video) {
try {
const promise =
video.play();
if (
promise &&
typeof promise.catch === 'function'
) {
return promise.catch(
() => false
);
}
return Promise.resolve(true);
} catch (e) {
return Promise.resolve(false);
}
}
/*
* =========================================================
* AUDIO
* =========================================================
*/
function rememberAudioUnlock() {
audioUnlocked = true;
try {
localStorage.setItem(
AUDIO_STORAGE_KEY,
'1'
);
} catch (e) {}
}
function formatTime(seconds) {
if (!Number.isFinite(seconds)) {
return '0:00';
}
seconds =
Math.max(
0,
Math.floor(seconds)
);
const minutes =
Math.floor(
seconds / 60
);
const secs =
seconds % 60;
return (
minutes +
':' +
String(secs).padStart(2, '0')
);
}
/*
* =========================================================
* FLASHVARS
* =========================================================
*/
function extractFlashvar(
html,
name
) {
const re =
new RegExp(
name +
'\\s*:\\s*[\'"]([^\'"]+)[\'"]'
);
const match =
html.match(re);
if (!match) {
return '';
}
return match[1]
.replace(
/&/g,
'&'
)
.replace(
/\\\//g,
'/'
);
}
/*
* =========================================================
* PEŁNY URL VIDEO
* =========================================================
*/
function loadFullVideoUrl(card) {
if (
fullVideoCache.has(card)
) {
return Promise.resolve(
fullVideoCache.get(card)
);
}
if (
fullVideoLoading.has(card)
) {
return fullVideoLoading.get(card);
}
const link =
card.querySelector(
'.js-click.hidden[data-href], .js-click[data-href]'
);
const href =
link
? link.getAttribute(
'data-href'
)
: '';
if (!href) {
return Promise.resolve('');
}
const promise =
fetch(
href,
{
credentials:
'include'
}
)
.then(response => {
if (!response.ok) {
throw new Error(
'HTTP ' +
response.status
);
}
return response.text();
})
.then(html => {
const url =
extractFlashvar(
html,
'video_alt_url2'
) ||
extractFlashvar(
html,
'video_alt_url'
) ||
extractFlashvar(
html,
'video_url'
) ||
extractFlashvar(
html,
'video_alt_url3'
);
if (url) {
fullVideoCache.set(
card,
url
);
}
return url;
})
.catch(() => '');
fullVideoLoading.set(
card,
promise
);
return promise;
}
/*
* =========================================================
* AUDIO OVERLAY
* =========================================================
*/
function showAudioOverlay() {
if (!audioOverlay) {
return;
}
audioOverlay.style.display =
'block';
}
function hideAudioOverlay() {
if (!audioOverlay) {
return;
}
audioOverlay.style.display =
'none';
}
function unlockAudio(event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
rememberAudioUnlock();
if (!zoomVideo) {
return;
}
zoomVideo.muted = false;
zoomVideo.volume = 1;
updateMuteButton();
safePlay(
zoomVideo
).then(success => {
if (success) {
hideAudioOverlay();
} else {
showAudioOverlay();
}
});
}
/*
* =========================================================
* DUŻY PREVIEW
* =========================================================
*/
function createZoom() {
if (zoomBox) {
return;
}
zoomBox =
document.createElement(
'div'
);
zoomBox.id =
'r34v802-zoom';
zoomVideo =
document.createElement(
'video'
);
zoomVideo.id =
'r34v802-video';
zoomVideo.autoplay = true;
zoomVideo.playsInline = true;
zoomVideo.preload = 'auto';
zoomVideo.muted =
!audioUnlocked;
zoomVideo.volume = 1;
zoomTitle =
document.createElement(
'div'
);
zoomTitle.id =
'r34v802-title';
const controls =
document.createElement(
'div'
);
controls.id =
'r34v802-controls';
zoomPlay =
document.createElement(
'button'
);
zoomPlay.type =
'button';
zoomPlay.textContent =
'▶';
zoomMute =
document.createElement(
'button'
);
zoomMute.type =
'button';
zoomProgress =
document.createElement(
'input'
);
zoomProgress.type =
'range';
zoomProgress.id =
'r34v802-progress';
zoomProgress.min = '0';
zoomProgress.max = '100';
zoomProgress.value = '0';
zoomProgress.step = '0.1';
zoomTime =
document.createElement(
'span'
);
zoomTime.id =
'r34v802-time';
zoomTime.textContent =
'0:00 / 0:00';
audioOverlay =
document.createElement(
'button'
);
audioOverlay.type =
'button';
audioOverlay.id =
'r34v802-audio';
audioOverlay.textContent =
'';
zoomBox.appendChild(
zoomVideo
);
zoomBox.appendChild(
zoomTitle
);
zoomBox.appendChild(
audioOverlay
);
controls.appendChild(
zoomPlay
);
controls.appendChild(
zoomMute
);
controls.appendChild(
zoomProgress
);
controls.appendChild(
zoomTime
);
zoomBox.appendChild(
controls
);
document.body.appendChild(
zoomBox
);
/*
* PLAY / PAUSE
*/
zoomPlay.addEventListener(
'click',
function (event) {
event.preventDefault();
event.stopPropagation();
if (
zoomVideo.paused
) {
safePlay(
zoomVideo
);
} else {
zoomVideo.pause();
}
}
);
/*
* KLIK VIDEO
*/
zoomVideo.addEventListener(
'click',
function (event) {
event.preventDefault();
event.stopPropagation();
if (
!audioUnlocked ||
zoomVideo.muted
) {
unlockAudio(
event
);
return;
}
if (
zoomVideo.paused
) {
safePlay(
zoomVideo
);
} else {
zoomVideo.pause();
}
}
);
/*
* MUTE
*/
zoomMute.addEventListener(
'click',
function (event) {
event.preventDefault();
event.stopPropagation();
if (
zoomVideo.muted
) {
rememberAudioUnlock();
zoomVideo.muted =
false;
zoomVideo.volume =
1;
updateMuteButton();
hideAudioOverlay();
safePlay(
zoomVideo
);
} else {
zoomVideo.muted =
true;
updateMuteButton();
}
}
);
audioOverlay.addEventListener(
'pointerdown',
unlockAudio
);
/*
* SEEK
*/
zoomProgress.addEventListener(
'input',
function () {
if (
!zoomVideo.duration
) {
return;
}
const value =
Number(
zoomProgress.value
) / 100;
try {
zoomVideo.currentTime =
zoomVideo.duration *
value;
} catch (e) {}
}
);
zoomVideo.addEventListener(
'timeupdate',
updateProgress
);
zoomVideo.addEventListener(
'loadedmetadata',
function () {
updateProgress();
updateMuteButton();
}
);
zoomVideo.addEventListener(
'play',
function () {
zoomPlay.textContent =
'❚❚';
}
);
zoomVideo.addEventListener(
'pause',
function () {
zoomPlay.textContent =
'▶';
}
);
zoomVideo.addEventListener(
'volumechange',
updateMuteButton
);
bindZoomHover();
updateMuteButton();
}
function updateMuteButton() {
if (
!zoomMute ||
!zoomVideo
) {
return;
}
zoomMute.textContent =
zoomVideo.muted
? '🔇'
: '🔊';
}
function updateProgress() {
if (
!zoomVideo ||
!zoomProgress ||
!zoomTime
) {
return;
}
const duration =
zoomVideo.duration || 0;
const current =
zoomVideo.currentTime || 0;
zoomProgress.value =
duration
? String(
(current /
duration) *
100
)
: '0';
zoomTime.textContent =
formatTime(
current
) +
' / ' +
formatTime(
duration
);
}
/*
* =========================================================
* POZYCJA DUŻEGO PREVIEW
* =========================================================
*/
function positionZoom(
titleElement
) {
if (!zoomBox) {
return;
}
const rect =
titleElement.getBoundingClientRect();
const width =
ZOOM_MAX_WIDTH;
const height =
width / ZOOM_RATIO;
/*
* Środek względem tytułu.
*/
const left =
rect.left +
(rect.width / 2) -
(width / 2);
/*
* ZAWSZE NAD TYTUŁEM.
*
* Nie ma fallbacku pod tytuł.
*/
const top =
rect.top -
height -
ZOOM_GAP;
/*
* NIE CLAMPUJEMY.
*
* Preview może wystawać
* poza viewport.
*/
zoomBox.style.width =
width + 'px';
zoomBox.style.height =
height + 'px';
zoomBox.style.left =
left + 'px';
zoomBox.style.top =
top + 'px';
}
/*
* =========================================================
* OTWARCIE DUŻEGO PREVIEW
* =========================================================
*/
function openZoom(
card,
titleElement
) {
if (
!card ||
!titleElement
) {
return;
}
const preview =
card.querySelector(
'.img.wrap_image[data-preview]'
);
if (!preview) {
return;
}
const previewUrl =
preview.getAttribute(
'data-preview'
);
if (!previewUrl) {
return;
}
createZoom();
clearTimeout(
hideTimer
);
currentCard =
card;
currentFullUrl =
'';
zoomOpen =
true;
const title =
card.querySelector(
'.thumb_title'
);
zoomTitle.textContent =
title
? title.textContent.trim()
: '';
positionZoom(
titleElement
);
zoomBox.style.display =
'block';
/*
* Najpierw szybki preview.
*/
zoomVideo.src =
previewUrl;
zoomVideo.muted =
!audioUnlocked;
zoomVideo.volume =
1;
updateMuteButton();
if (audioUnlocked) {
hideAudioOverlay();
} else {
showAudioOverlay();
}
safePlay(
zoomVideo
);
/*
* Następnie pobieramy pełny URL.
*/
loadFullVideoUrl(
card
)
.then(fullUrl => {
if (!fullUrl) {
return;
}
if (
!zoomOpen ||
currentCard !== card
) {
return;
}
if (
fullUrl ===
currentFullUrl
) {
return;
}
currentFullUrl =
fullUrl;
zoomVideo.src =
fullUrl;
zoomVideo.muted =
!audioUnlocked;
zoomVideo.volume =
1;
zoomVideo.load();
const restoreAndPlay =
function () {
zoomVideo.removeEventListener(
'loadedmetadata',
restoreAndPlay
);
if (
!zoomOpen ||
currentCard !== card
) {
return;
}
updateMuteButton();
safePlay(
zoomVideo
).then(
success => {
if (
audioUnlocked &&
!success
) {
showAudioOverlay();
}
}
);
};
zoomVideo.addEventListener(
'loadedmetadata',
restoreAndPlay
);
});
}
/*
* =========================================================
* ZAMYKANIE DUŻEGO PREVIEW
* =========================================================
*/
function scheduleClose() {
clearTimeout(
hideTimer
);
hideTimer =
setTimeout(
function () {
if (!zoomBox) {
return;
}
if (
zoomBox.matches(
':hover'
)
) {
return;
}
zoomOpen =
false;
zoomBox.style.display =
'none';
if (zoomVideo) {
zoomVideo.pause();
}
currentCard =
null;
currentFullUrl =
'';
},
120
);
}
/*
* =========================================================
* HOVER TYTUŁU
* =========================================================
*/
function bindTitle(
titleElement
) {
if (
titleElement.dataset
.r34v802Bound
) {
return;
}
titleElement.dataset
.r34v802Bound =
'1';
titleElement.addEventListener(
'mouseenter',
function () {
const card =
titleElement.closest(
'.item.thumb[data-video-card-id]'
);
if (!card) {
return;
}
clearTimeout(
hoverTimers.get(
titleElement
)
);
const timer =
setTimeout(
function () {
hoverTimers.delete(
titleElement
);
if (
!titleElement.matches(
':hover'
)
) {
return;
}
openZoom(
card,
titleElement
);
},
HOVER_DELAY
);
hoverTimers.set(
titleElement,
timer
);
}
);
titleElement.addEventListener(
'mouseleave',
function () {
clearTimeout(
hoverTimers.get(
titleElement
)
);
hoverTimers.delete(
titleElement
);
scheduleClose();
}
);
}
/*
* =========================================================
* HOVER DUŻEGO PREVIEW
* =========================================================
*/
function bindZoomHover() {
if (
!zoomBox ||
zoomBox.dataset.bound
) {
return;
}
zoomBox.dataset.bound =
'1';
zoomBox.addEventListener(
'mouseenter',
function () {
clearTimeout(
hideTimer
);
}
);
zoomBox.addEventListener(
'mouseleave',
function () {
scheduleClose();
}
);
}
/*
* =========================================================
* MAŁE VIDEO NA KAFELKACH
*
* WAŻNE:
*
* NIE MA tutaj IntersectionObserver,
* który zatrzymuje video.
*
* Kafelki mają cały czas:
*
* autoplay
* loop
* muted
*
* =========================================================
*/
function startCardPreview(
card
) {
if (
!card ||
card.dataset.r34v802Preview
) {
return;
}
const wrap =
card.querySelector(
'.img.wrap_image[data-preview]'
);
if (!wrap) {
return;
}
const url =
wrap.getAttribute(
'data-preview'
);
if (!url) {
return;
}
card.dataset.r34v802Preview =
'1';
wrap.classList.add(
'r34v802-preview-wrap'
);
/*
* Nie twórz drugiego video,
* jeśli skrypt wykona skan ponownie.
*/
const existingVideo =
wrap.querySelector(
'.r34v802-card-video'
);
if (existingVideo) {
safePlay(
existingVideo
);
return;
}
const video =
document.createElement(
'video'
);
video.className =
'r34v802-card-video';
video.src =
url;
/*
* ==============================================
* NAJWAŻNIEJSZE:
*
* KAFELKI GRAJĄ CAŁY CZAS.
* ==============================================
*/
video.autoplay =
true;
video.loop =
true;
video.muted =
true;
video.defaultMuted =
true;
video.volume =
0;
video.playsInline =
true;
video.preload =
'auto';
/*
* Nie pozwalamy kliknięciu video
* przejąć kliknięcia kafelka.
*/
video.style.pointerEvents =
'none';
/*
* Obrazek pozostaje widoczny,
* dopóki video nie ma gotowej klatki.
*/
video.style.opacity =
'0';
let videoReady =
false;
function showVideo() {
if (videoReady) {
return;
}
videoReady =
true;
video.classList.add(
'r34v802-ready'
);
}
/*
* Gdy video faktycznie ma dane.
*/
video.addEventListener(
'loadeddata',
showVideo
);
video.addEventListener(
'canplay',
showVideo
);
video.addEventListener(
'playing',
showVideo
);
/*
* Jeśli video się wysypie,
* wracamy do obrazka.
*/
video.addEventListener(
'error',
function () {
videoReady =
false;
video.classList.remove(
'r34v802-ready'
);
video.style.opacity =
'0';
}
);
/*
* Jeżeli przeglądarka z jakiegoś
* powodu zatrzyma autoplay,
* próbujemy ponownie.
*/
video.addEventListener(
'pause',
function () {
/*
* Nie wymuszamy natychmiastowego
* play w pętli eventowej.
*
* Mała zwłoka pozwala przeglądarce
* poprawnie obsłużyć zmianę stanu.
*/
setTimeout(
function () {
if (
document.contains(
video
)
) {
safePlay(
video
);
}
},
100
);
}
);
/*
* Dodajemy video NAD obrazkiem.
*
* Obrazek NIE jest ukrywany.
*/
wrap.appendChild(
video
);
/*
* Start natychmiast.
*/
safePlay(
video
);
}
/*
* =========================================================
* SKANOWANIE KAFELKÓW
* =========================================================
*/
function scanCards() {
const cards =
document.querySelectorAll(
'.item.thumb[data-video-card-id]'
);
cards.forEach(
card => {
const title =
card.querySelector(
'.thumb_title'
);
if (title) {
bindTitle(
title
);
}
/*
* WAŻNE:
*
* Nie używamy tutaj
* IntersectionObserver.
*
* Każdy znaleziony kafelek
* dostaje swoje video.
*/
startCardPreview(
card
);
}
);
bindZoomHover();
}
/*
* =========================================================
* OBSERWATOR DYNAMICZNYCH KAFELKÓW
* =========================================================
*/
const mutationObserver =
new MutationObserver(
function () {
scanCards();
}
);
mutationObserver.observe(
document.body,
{
childList: true,
subtree: true
}
);
/*
* =========================================================
* RESIZE
* =========================================================
*/
window.addEventListener(
'resize',
function () {
if (
zoomOpen &&
currentCard
) {
const title =
currentCard.querySelector(
'.thumb_title'
);
if (title) {
positionZoom(
title
);
}
}
}
);
/*
* =========================================================
* SCROLL
* =========================================================
*
* Małe video na kafelkach NIE jest
* tutaj zatrzymywane.
*
* Aktualizujemy tylko pozycję
* dużego preview.
* =========================================================
*/
window.addEventListener(
'scroll',
function () {
if (
zoomOpen &&
currentCard
) {
const title =
currentCard.querySelector(
'.thumb_title'
);
if (title) {
positionZoom(
title
);
}
}
},
{
passive: true
}
);
/*
* =========================================================
* START
* =========================================================
*/
scanCards();
})();