Old Reddit Auto-Expand Gallery & Show Thumbnails

Auto-expand the gallery and keep displaying the thumbnail grid to switch pictures.

// ==UserScript==
// @name         Old Reddit Auto-Expand Gallery & Show Thumbnails
// @description  Auto-expand the gallery and keep displaying the thumbnail grid to switch pictures.
// @author       C89sd
// @version      1.2
// @match        https://old.reddit.com/r/*/comments/*
// @grant        GM_addStyle
// @namespace    https://greasyfork.org/users/1376767
// @noframes
// ==/UserScript==
'use strict';

// hide Previous Next butttons
// hide Back to Grid View
GM_addStyle(`
.gallery-tiles   { display: block !important; }
.gallery-nav-bar { display: none  !important; }
`);

const __THUMBNAIL     = '.expando .gallery-navigation[data-action="preview"]'; // clickable thumbnail
const __PREVIEW       = '.expando .gallery-preview';

// https://old.reddit.com/r/pics/comments/1kqlqe8/            .expando, single, auto expands + auto focus
// https://old.reddit.com/r/pics/comments/1kqd4i4/            .expando, many, expand and focus
// https://old.reddit.com/r/oddlyterrifying/comments/1d55cch/ .expando-uninitialized, single, load button expand and focus
// https://old.reddit.com/r/oddlyterrifying/comments/1k9kzdy/ .expando-uninitialized, many, load button expand and focus
const expando = document.querySelector('.expando');
if (expando) {
  if (expando.classList.contains('expando-uninitialized')) {
    // Wait for load
    const observer = new MutationObserver((mutations, obs) => {
        obs.disconnect();
        hideAllPreviewsOnThumbnailClick();
        focusFirstPreview();
    });
    observer.observe(expando, {childList: true});

    // Click load button (in document scope is fine for your case)
    const button = document.querySelector('.expando-button');
    if (button) button.click();
  } else {
    hideAllPreviewsOnThumbnailClick();
    focusFirstPreview();
  }
}

function focusFirstPreview() {
  const prev = document.querySelector(__PREVIEW);
  if (prev) prev.style.display = 'block';
}

function hideAllPreviewsOnThumbnailClick() {
  const thumbnails = document.querySelectorAll(__THUMBNAIL);
  const previews = document.querySelectorAll(__PREVIEW);

  for (let [i, thumbnail] of thumbnails.entries()) {
    thumbnail.addEventListener('click', () => {
      for (let [j, preview] of previews.entries()) {
        preview.style.display = (i === j) ? 'block' : 'none';
      }
    });
  }
}