Squabbles.io Sort Communities

Sort subscribed communities on your home page.

As of 2023-06-14. See the latest version.

// ==UserScript==
// @name         Squabbles.io Sort Communities
// @namespace  https://github.com/waaamb/userscripts
// @version      0.2.2
// @description  Sort subscribed communities on your home page.
// @author       Waaamb
// @match        *://*.squabbles.io/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=squabbles.io
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    /* Settings */
    /* These are settings variables to enable features.
    /* Keep in mind they'll be erased if the script is updated.              */

    // This does nothing right now. The script only sorts alphabetically.
    const sortMode = 'aza';

    /* Currently the list of communities on your home page is unsorted.
    /* This function sorts them.                                             */

    let oldSquubsListLength = 0;

    function sortSquubs() {
        // Select the list of squubs
        const squubsListDiv = selectSquubsList();

        if (squubsListDiv) {
            const squubsList = Array.from(squubsListDiv.children);

            if (squubsList.length != oldSquubsListLength) {
                squubsListDiv.classList.remove('sorted');
            }

            if (!squubsListDiv.classList.contains('sorted')) {

                // Sort the list alphabetically
                // This could be changed to incorporate different sorting methods
                let sortedSquubs = squubsList.sort((a, b) => a.textContent.localeCompare(b.textContent));
                // Move the "more" button back to the end
                sortedSquubs.push(sortedSquubs.shift());

                oldSquubsListLength = sortedSquubs.length;
                squubsListDiv.append(...sortedSquubs);
                squubsListDiv.classList.add('sorted');
                console.log('Sorted squubs list');
            }
        }
    }

    // This could break at any time if elements are added to or deleted from the page
    // Hopefully the list gets an actual identifier in the future
    const selectSquubsList = () => {
        let squubsListDiv = document.querySelector('#app #content-wrapper .container div')

        if (squubsListDiv && squubsListDiv.parentNode.textContent.includes("Home page")) {
            if (!squubsListDiv.classList.contains('squubs-list')) {
                squubsListDiv.classList.add('squubs-list');
            }
            return squubsListDiv;
        }
    }

    const observeDOM = (fn, e = document.documentElement, config = { attributes: 1, childList: 1, subtree: 1 }) => {
        const observer = new MutationObserver(fn);
        observer.observe(e, config);
        return () => observer.disconnect();
    };

    observeDOM(sortSquubs);
})();