YouTube 6 Videos Per Row (Updated)

Forces YouTube homepage to show 6 videos per row by adjusting the grid layout

// ==UserScript==
// @name         YouTube 6 Videos Per Row (Updated)
// @namespace    http://tampermonkey.net/
// @version      1.1
// @license MIT
// @description  Forces YouTube homepage to show 6 videos per row by adjusting the grid layout
// @author       mechanicalfluff
// @match        https://www.youtube.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    // Function to apply the 6 videos per row style
    function applyLayoutFix() {
        const styleId = 'youtube-6-videos-per-row-updated';
        // Remove existing style if it exists to avoid duplicates
        const existingStyle = document.getElementById(styleId);
        if (existingStyle) {
            existingStyle.remove();
        }

        // Create and append new style element
        const style = document.createElement('style');
        style.id = styleId;
        style.textContent = `
            #contents.ytd-rich-grid-renderer {
                display: flex !important;
                flex-wrap: wrap !important;
                gap: 12px !important;
            }
            ytd-rich-grid-row {
                display: contents !important;
            }
            ytd-rich-item-renderer {
                flex: 0 0 calc(16.66% - 10px) !important; /* 16.66% = 100% / 6, minus some gap */
                max-width: calc(16.66% - 10px) !important;
                margin-bottom: 12px !important;
            }
        `;
        document.head.appendChild(style);
    }

    // Apply fix on initial page load
    window.addEventListener('load', applyLayoutFix);

    // Re-apply fix on navigation (YouTube uses AJAX for navigation)
    window.addEventListener('yt-navigate-finish', applyLayoutFix);

    // MutationObserver to handle dynamic content changes
    const observer = new MutationObserver((mutations) => {
        mutations.forEach(() => {
            applyLayoutFix();
        });
    });

    // Observe changes to the body to catch dynamic updates
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // Initial application in case the page is already loaded
    applyLayoutFix();
})();