Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function fixIndents(e) {
    if (newHTML) {
        document.querySelector(".mw-parser-output").innerHTML = newHTML;
        mw.util.hidePortlet(portFixId);
        mw.util.showPortlet(portUnfixId);
    } else {
        var pageName = mw.config.get("wgPageName");
        var urlencodedPageName = mw.util.rawurlencode(pageName);
        var revisionId = mw.config.get("wgRevisionId");
        var getHTMLurl = "https://en.wikipedia.org/api/rest_v1/page/html/" + urlencodedPageName + "/" + revisionId;
        $.ajax(getHTMLurl, {
            type: "GET",
            headers: {
                accept: 'text/html; charset=utf-8"',
                "Content-Type": "application/json",
            },
        })
            .then(function (html, textStatus, jqXHR) {
                console.log("original html");
                console.log(html);
                //html = tweakHTML(html);
                return $.ajax(
                    "https://en.wikipedia.org/api/rest_v1/transform/html/to/wikitext/" +
                        urlencodedPageName +
                        "/" +
                        revisionId,
                    {
                        type: "POST",
                        headers: {
                            accept: "text/plain; charset=utf-8",
                            "Content-Type": "application/json",
                            "if-match": jqXHR.getResponseHeader("etag"),
                        },
                        data: JSON.stringify({
                            html: html,
                            scrub_wikitext: true,
                        }),
                    }
                );
            })
            .then(function (wikitext, textStatus, jqXHR) {
                console.log(wikitext);
                return $.ajax(
                    "https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html/" +
                        urlencodedPageName +
                        "/" +
                        revisionId,
                    {
                        type: "POST",
                        headers: {
                            accept: "text/html; charset=utf-8",
                            "Content-Type": "application/json",
                        },
                        data: JSON.stringify({
                            body_only: true,
                            wikitext: wikitext,
                        }),
                    }
                );
            })
            .then(function (data) {
                console.log("final HTML");
                console.log(data);
                newHTML = data;
                document.querySelector(".mw-parser-output").innerHTML = data;
                mw.util.hidePortlet(portFixId);
                mw.util.showPortlet(portUnfixId);
            });
    }

    e.preventDefault();
}

function tweakHTML(html) {
    var parser = new DOMParser();
    var htmlDoc = parser.parseFromString(html, "text/html");
    var nodes = document.createTreeWalker(
        htmlDoc.querySelector(".mw-parser-output"),
        NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
        function (n) {
            if (n.nodeName === "PRE") {
                return NodeFilter.FILTER_REJECT;
            } else if (n.nodeName === "#text") {
                return NodeFilter.FILTER_ACCEPT;
            }
            return NodeFilter.FILTER_SKIP;
        }
    );
    var node;
    while ((node = nodes.nextNode())) {
        if (!node.previousSibling) {
            node.textContent = node.textContent.replace(/^\s+/, " ");
        }
    }
    return htmlDoc.documentElement.outerHTML;
}

function shouldFix() {
    if (mw.config.get("wgAction") !== "view") {
        return false;
    }
    return mw.config.get("wgNamespaceNumber") % 2 === 1;
}

var portFixId = "ca-fix-indents";
var portUnfixId = "ca-unfix-indents";
var originalHTML; // cache the original html
var newHTML; // cache the fixed html


$(document).ready(function () {
    if (!shouldFix()) {
        return;
    }
    console.log(mw.config.get("wgPageName"), mw.config.get("wgRevisionId"));
    originalHTML = document.querySelector(".mw-parser-output").innerHTML;
    var portFix = mw.util.addPortletLink(
        "p-cactions",
        "#",
        "Fix indents",
        portFixId,
        "Fix list indentation for screen readers"
    );
    var portUnfix = mw.util.addPortletLink(
        "p-cactions",
        "#",
        "Unfix indents",
        portUnfixId,
        "Reset to original indentation"
    );
    mw.util.hidePortlet(portUnfixId);
    $(portFix).on("click", fixIndents);
    $(portUnfix).on("click", function (e) {
        document.querySelector(".mw-parser-output").innerHTML = originalHTML;
        mw.util.hidePortlet(portUnfixId);
        mw.util.showPortlet(portFixId);
        e.preventDefault();
    });
});