Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name Reddit Gallery Justified Grid & Full-Res Opener
- // @namespace https://tampermonkey.net/
- // @version 5.4
- // @description Эргономичная укладка фото на Reddit в плитку + открытие оригиналов по ЛКМ и колесику для любых постов
- // @author You
- // @match https://*.reddit.com/*
- // @grant GM_addStyle
- // @grant GM_openInTab
- // @run-at document-idle
- // ==/UserScript==
- (function() {
- 'use strict';
- const css = `
- /* 1. Снимаем обрезку по высоте для одиночных картинок в ленте */
- div[slot="post-media-container"] {
- height: auto !important;
- max-height: none !important;
- overflow: visible !important;
- }
- div[slot="post-media-container"] img {
- cursor: pointer !important;
- max-height: 85vh !important;
- object-fit: contain !important;
- }
- /* Обертка-ссылка для одиночных картинок (display: contents не ломает верстку) */
- .reddit-single-img-link {
- display: contents !important;
- cursor: pointer !important;
- }
- /* 2. Контейнер умной укладки (заполняет 100% ширины) */
- .reddit-custom-grid {
- --row-height: 220px;
- display: flex !important;
- flex-wrap: wrap !important;
- gap: 8px !important;
- width: 100% !important;
- margin: 8px 0 16px 0 !important;
- box-sizing: border-box !important;
- }
- /* Ячейка плитки */
- .reddit-custom-grid-item {
- position: relative !important;
- flex-grow: var(--ar, 1) !important;
- flex-shrink: 1 !important;
- flex-basis: calc(var(--ar, 1) * var(--row-height)) !important;
- aspect-ratio: var(--ar, 1) !important;
- max-height: 520px !important;
- min-width: 120px !important;
- border-radius: 8px !important;
- overflow: hidden !important;
- background: #141414 !important;
- box-shadow: 0 1px 4px rgba(0,0,0,0.25) !important;
- }
- .reddit-custom-grid-item a {
- display: block !important;
- width: 100% !important;
- height: 100% !important;
- cursor: pointer !important;
- }
- .reddit-custom-grid-item img {
- width: 100% !important;
- height: 100% !important;
- object-fit: cover !important;
- display: block !important;
- transition: transform 0.2s ease, filter 0.2s ease !important;
- }
- .reddit-custom-grid-item:hover img {
- transform: scale(1.03) !important;
- filter: brightness(1.06) !important;
- }
- /* Бейдж с номером фото */
- .reddit-custom-grid-badge {
- position: absolute !important;
- bottom: 6px !important;
- right: 6px !important;
- background: rgba(0, 0, 0, 0.72) !important;
- color: #fff !important;
- font-size: 11px !important;
- font-weight: 600 !important;
- padding: 2px 6px !important;
- border-radius: 4px !important;
- pointer-events: none !important;
- font-family: sans-serif !important;
- backdrop-filter: blur(2px) !important;
- }
- `;
- if (typeof GM_addStyle !== 'undefined') {
- GM_addStyle(css);
- } else {
- const style = document.createElement('style');
- style.textContent = css;
- document.head.appendChild(style);
- }
- // Получение ссылки на оригинальное фото
- function getFullImageUrl(post, mediaContainer, img) {
- let fullUrl = null;
- const contentHref = post?.getAttribute('content-href');
- if (contentHref && (contentHref.includes('i.redd.it') || /\.(jpg|jpeg|png|webp|gif)(\?.*)?$/i.test(contentHref))) {
- fullUrl = contentHref;
- }
- if (!fullUrl) {
- const lightboxImg = mediaContainer?.querySelector('.lightboxed-content img');
- if (lightboxImg?.src) fullUrl = lightboxImg.src;
- }
- if (!fullUrl && img?.src) {
- if (img.src.includes('preview.redd.it')) {
- fullUrl = img.src.replace(/https:\/\/(?:preview|i)\.redd\.it\/([^?]+).*/, 'https://i.redd.it/$1');
- } else {
- fullUrl = img.src;
- }
- }
- return fullUrl;
- }
- // 1. Обработка галерей (много картинок -> в умную плитку)
- function processGallery(carousel) {
- if (carousel.dataset.customGridDone === 'true') return;
- const listItems = carousel.querySelectorAll('ul > li');
- if (!listItems || listItems.length === 0) return;
- const images = [];
- listItems.forEach(li => {
- const fullImg = li.querySelector('.lightboxed-content img');
- const figureImg = li.querySelector('figure img.media-lightbox-img') || li.querySelector('figure img');
- const fullUrl = fullImg?.src || figureImg?.src;
- const previewUrl = figureImg?.src || fullUrl;
- const width = parseInt(figureImg?.getAttribute('width')) || parseInt(fullImg?.getAttribute('width')) || 0;
- const height = parseInt(figureImg?.getAttribute('height')) || parseInt(fullImg?.getAttribute('height')) || 0;
- const ar = (width && height) ? (width / height).toFixed(3) : null;
- if (previewUrl) {
- images.push({
- full: fullUrl,
- preview: previewUrl,
- alt: figureImg?.alt || '',
- ar: ar
- });
- }
- });
- if (images.length > 0) {
- carousel.dataset.customGridDone = 'true';
- const grid = document.createElement('div');
- grid.className = 'reddit-custom-grid';
- images.forEach((imgData, index) => {
- const item = document.createElement('div');
- item.className = 'reddit-custom-grid-item';
- if (imgData.ar) {
- item.style.setProperty('--ar', imgData.ar);
- }
- const link = document.createElement('a');
- link.href = imgData.full;
- link.target = '_blank';
- link.title = 'Открыть оригинал';
- link.addEventListener('click', (e) => e.stopPropagation());
- link.addEventListener('auxclick', (e) => e.stopPropagation());
- const img = document.createElement('img');
- img.src = imgData.preview;
- img.alt = imgData.alt;
- img.loading = 'lazy';
- if (!imgData.ar) {
- img.onload = () => {
- if (img.naturalWidth && img.naturalHeight) {
- const naturalAr = (img.naturalWidth / img.naturalHeight).toFixed(3);
- item.style.setProperty('--ar', naturalAr);
- }
- };
- }
- const badge = document.createElement('span');
- badge.className = 'reddit-custom-grid-badge';
- badge.textContent = `${index + 1}/${images.length}`;
- link.appendChild(img);
- item.appendChild(link);
- item.appendChild(badge);
- grid.appendChild(item);
- });
- carousel.style.setProperty('display', 'none', 'important');
- carousel.parentNode.insertBefore(grid, carousel);
- }
- }
- // 2. Обработка постов с 1 картинкой (оборачиваем в нативную ссылку <a> для поддержки колесика)
- function processSingleImages() {
- const containers = document.querySelectorAll('div[slot="post-media-container"]');
- containers.forEach(container => {
- if (container.dataset.singleDone === 'true') return;
- if (container.querySelector('.reddit-custom-grid')) return;
- if (container.querySelector('shreddit-player')) return;
- if (container.querySelector('gallery-carousel')) return;
- const img = container.querySelector('img.media-lightbox-img') ||
- container.querySelector('figure img') ||
- container.querySelector('img');
- if (!img) return;
- const post = container.closest('shreddit-post');
- const fullUrl = getFullImageUrl(post, container, img);
- if (!fullUrl) return;
- container.dataset.singleDone = 'true';
- if (img.parentElement && img.parentElement.classList.contains('reddit-single-img-link')) return;
- const link = document.createElement('a');
- link.className = 'reddit-single-img-link';
- link.href = fullUrl;
- link.target = '_blank';
- link.title = 'Открыть оригинал';
- link.addEventListener('click', (e) => e.stopPropagation());
- link.addEventListener('auxclick', (e) => e.stopPropagation());
- img.parentNode.insertBefore(link, img);
- link.appendChild(img);
- });
- }
- function checkAllPosts() {
- document.querySelectorAll('gallery-carousel').forEach(processGallery);
- processSingleImages();
- }
- // Предотвращаем появление значка кругового автоскролла при клике колёсиком по картинке
- document.addEventListener('mousedown', (e) => {
- if (e.button === 1 && e.target.closest('div[slot="post-media-container"] img')) {
- e.stopPropagation();
- }
- }, true);
- const observer = new MutationObserver(() => {
- checkAllPosts();
- });
- observer.observe(document.body, { childList: true, subtree: true });
- checkAllPosts();
- })();
Advertisement
Add Comment
Please, Sign In to add comment