Add non-MFC figure

Track preordered non-MFC items on collection screen

// ==UserScript==
// @name         Add non-MFC figure
// @namespace    https://tharglet.me.uk
// @version      1.7
// @description  Track preordered non-MFC items on collection screen
// @author       Tharglet
// @match        https://myfigurecollection.net/users.v4.php?*mode=view&*tab=collection&*
// @grant        GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==

//Polyfill for GM_addStyle for Greasemonkey...
if(typeof GM_addStyle == 'undefined') {
    GM_addStyle = (aCss) => {
        'use strict';
        let head = document.getElementsByTagName('head')[0];
        if (head) {
            let style = document.createElement('style');
            style.setAttribute('type', 'text/css');
            style.textContent = aCss;
            head.appendChild(style);
            return style;
        }
        return null;
    };
}

GM_addStyle(`
.non-mfc-item__tray-icon {
border: green 1px solid;
display: block;
margin: 8px;
padding: 1px;
}
.non-mfc-item__icon-container {
float: left;
margin-bottom: 20px;
}
.non-mfc-item__tray-icon img {
width: 60px;
height: 60px;
border-radius: 2px;
}
.non-mfc-item__edit, .non-mfc-item__delete {
display: inline-block;
}

.non-mfc-item__edit span, .non-mfc-item__delete span {
font-size: 16px;
margin: 0 4px;
}
`);

(function() {
    'use strict';
    let BASE_COUNT = 0;
    var isUsersPreorderPage = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const status = urlParams.get("status");
        if(status == 1) {
            let loggedInUser = $(".user-menu .handle");
            if(loggedInUser) {
                let userLink = loggedInUser.attr("href");
                if(userLink === "/session/signup") {
                    return false;
                } else {
                    let userParam;
                    const windowLocation = window.location.href;
                    if(windowLocation.startsWith("https://myfigurecollection.net/profile/")) {
                        userParam = windowLocation.match(/https:\/\/myfigurecollection\.net\/profile\/([^\/]*)/)[1];
                    } else {
                        const urlParams = new URLSearchParams(window.location.search);
                        userParam = urlParams.get("username");
                    }
                    return userParam === userLink.substring("9");
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    var additionalFigures = JSON.parse(GM_getValue("additionalFigures", "[]"));
    var resetNonMfcItemForm = () => {
        $("#non-mfc-item__form-title").text('Add non-MFC figure');
        $("#addNonMfcItem").text("Add");
        $("#nonMfcItemEditId").val("");
        $("#nonMfcItemName").val("");
        $("#nonMfcItemImage").val("");
        $("#nonMfcItemLink").val("");
        $("#nonMfcItemReleaseDate").val("");
    }

    var drawAdditionalFigures = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const sortType = urlParams.get("sort") || "category";
        const output = urlParams.get("output");
        //Clear all additions before redo
        $("#nonMfcAdditions").remove();
        $(".non-mfc-item__icon").remove();
        $(".non-mfc-item__edit").remove();
        $(".non-mfc-item__delete").remove();
        $(".non-mfc-item__year-header").remove();
        if(additionalFigures.length > 0) {
            //update item count
            let totalFigureCount = BASE_COUNT + additionalFigures.length;
            $('.listing-link-toggle.on .count').text(totalFigureCount);
            $('.listing-count-value').get(0).lastChild.nodeValue = `${totalFigureCount} items`;
            //Pre-add setup
            const addList = $("#nonMfcFigureList");
            let dateHeadings;
            if(sortType == "groupByReleaseDates") {
                if(output === "0") {
                    dateHeadings = $("li.listing-title");
                } else {
                    dateHeadings = $(".listing-item h3");

                }
            } else if(sortType.startsWith("groupBy")) {
                if(output === "0") {
                    $(".listing-toggles:last").after('<li id="nonMfcAdditions" class="listing-title">Non-MFC</li>');
                } else {
                    $(".listing-item .item-icons").prepend('<div class="item-group-by" id="nonMfcAdditions"><h3>Non-MFC</h3></div>');
                }

            }
            //Add icons to page and delete box
            additionalFigures.forEach((fig, idx) => {
                let linkLine;
                const figYear = fig.date.substring(0, 4);
                const figMonth = fig.date.substring(5);
                const figureThumb = `<span class="non-mfc-item__icon item-icon">
<a href="${fig.link}" class="tbx-tooltip item-root-0 item-category-1">
<img src="${fig.image}">
</a>
</span>`;
                if(output === "0") {
                    linkLine = `<div class='listing-item non-mfc-item__icon'><div class="stamp item-stamp">
<a href="/item/872779" class="tbx-tooltip">
<img class="stamp-icon" src="${fig.image}"</a><div class="stamp-anchor"><a class="tbx-tooltip item-category-1" href="${fig.link}">${fig.name}</a>
</div></div></div>`
                }
                addList.append(`<span class='non-mfc-item__icon-container'>
                ${figureThumb.replace('item-icon', 'non-mfc-item__tray-icon')}
                <a href="#" class='non-mfc-item__edit' title="Edit" data-index="${idx}"><span class="tiny-icon-only icon-pencil-square-o" data-index="${idx}"></span></a>
                <a href="#" class='non-mfc-item__delete' title="Delete" data-index="${idx}"><span class="tiny-icon-only icon-trash-o" data-index="${idx}"></span></a>
                </span>`);
                let toAppend = true;
                if(sortType == "groupByReleaseDates") {
                    dateHeadings.each((idx, heading) => {
                        if(toAppend) {
                            const headingYear = $(heading).text().substring(0,4);
                            const headingMonth = $(heading).text().substring(5);
                            if(figYear == headingYear && figMonth == headingMonth) {
                                if(output === "0") {
                                    $(heading).after(linkLine);
                                } else {
                                    $(heading).after(figureThumb);
                                }
                                toAppend = false;
                            } else if(new Date(figYear, figMonth, 1) > new Date(headingYear, headingMonth, 1)) {
                                if(output === "0") {
                                    const newHeading = `<li class="listing-title non-mfc-item__year-header" id='nhi_${idx}'>${figYear}-${figMonth}</li></h3>`
                                    $(heading).before(newHeading + linkLine);
                                } else {
                                    const newHeading = `<h3 class="non-mfc-item__year-header" id='nhi_${idx}'>${figYear}-${figMonth}</h3>`
                                    $(heading).before(newHeading + figureThumb);
                                }
                                dateHeadings.splice(idx, 0, $(`#nhi_${idx}`));
                                toAppend = false;
                            }
                        }
                    });
                    //Append if trailing
                    if(toAppend) {
                        const newHeading = `<h3 class="non-mfc-item__year-header" id='nhi_${idx}'>${figYear}-${figMonth}</h3>`
                        $('.item-group-by:last').after('<div class="item-group-by">' + newHeading + figureThumb + '</div>');
                        dateHeadings.push($(`#nhi_${idx}`));
                    }
                } else if(sortType.startsWith("groupBy")) {
                    if(output === "0") {
                        $("#nonMfcAdditions").after(linkLine)
                    } else {
                        $("#nonMfcAdditions h3").after(figureThumb);
                    }
                } else {
                    if(output === "0") {
                        $(".listing-toggles:last").after(linkLine);
                    } else {
                        $(".listing-item .item-icons").prepend(figureThumb);
                    }
                }
            });
            $('.non-mfc-item__delete').click((evt) => {
                evt.preventDefault();
                if(confirm("Delete this figure?")) {
                    additionalFigures.splice($(evt.target).attr("data-index"), 1);
                    additionalFigures.sort((a, b) => (a.date < b.date) ? 1 : -1);
                    GM_setValue("additionalFigures", JSON.stringify(additionalFigures));
                    drawAdditionalFigures();
                    resetNonMfcItemForm();
                }
            });
            $('.non-mfc-item__edit').click((evt) => {
                evt.preventDefault();
                var figToEdit = additionalFigures[$(evt.target).attr("data-index")];
                $("#non-mfc-item__form-title").text(`Editing ${figToEdit.name}`);
                $("#addNonMfcItem").text("Edit");
                $("#nonMfcItemEditId").val($(evt.target).attr("data-index"));
                $("#nonMfcItemName").val(figToEdit.name);
                $("#nonMfcItemImage").val(figToEdit.image);
                $("#nonMfcItemLink").val(figToEdit.link);
                $("#nonMfcItemReleaseDate").val(figToEdit.date);
                $([document.documentElement, document.body]).animate({
                    scrollTop: $("#non-mfc-item__section").offset().top - 100
                }, 200);
            });
            $("#cancelNonMfcItem").click((evt) => {
                evt.preventDefault();
                if(confirm("Are you sure you want to cancel?")) {
                    resetNonMfcItemForm();
                }
            });
        }
    }

    $().ready(() => {
        BASE_COUNT = parseInt($('.listing-link-toggle.on .count').text());
        if(isUsersPreorderPage()) {
            const addSection = `<section id='non-mfc-item__section'>
<h2 id='non-mfc-item__form-title'>Add non-MFC figure</h2>
<div class='form'>
<input type='hidden' id='nonMfcItemEditId' value=''/>
<div class='bigchar form-field'>
<div class='form-label'>Figure name</div>
<div class='form-input'><input type='text' id='nonMfcItemName'/></div>
</div>
<div class='bigchar form-field'>
<div class='form-label'>Image URL *</div>
<div class='form-input'><input type='text' id='nonMfcItemImage'/></div>
</div>
<div class='bigchar form-field'>
<div class='form-label'>Item link *</div>
<div class='form-input'><input type='text' id='nonMfcItemLink'/></div>
</div>
<div class='bigchar form-field'>
<div class='form-label'>Release date (YYYY-MM) *</div>
<div class='form-input'><input type='text' id='nonMfcItemReleaseDate'/></div>
</div>
<div class='form-field'>
<div class='form-input'>
<button id='addNonMfcItem'>Add</button>
<button id='cancelNonMfcItem'>Cancel</button>
</div>
</div>
</div>
</section>
<section>
<h2>Added non-MFC figures</h2>
<div class='form'>
<div id='nonMfcFigureList' class='item-icons'>
</div>
</div>
</section>`
            $("#side section:last").after(addSection);
            drawAdditionalFigures();
            $("#addNonMfcItem").click((e) => {
                e.preventDefault();
                const name = $("#nonMfcItemName").val() || "Non-MFC figure";
                const image = $("#nonMfcItemImage").val();
                const link = $("#nonMfcItemLink").val();
                const date = $("#nonMfcItemReleaseDate").val();
                const editId = $("#nonMfcItemEditId").val();
                if(image && link && date && name) {
                    if(date.match(/^\d{4}-0[1-9]|1[0-2]$/)) {
                        if(editId) {
                            additionalFigures[editId] = {
                                name: name,
                                image: image,
                                link: link,
                                date: date
                            }
                        } else {
                            additionalFigures.push({
                                name: name,
                                image: image,
                                link: link,
                                date: date
                            });
                        }
                        additionalFigures.sort((a, b) => (a.date < b.date) ? 1 : -1);
                        GM_setValue("additionalFigures", JSON.stringify(additionalFigures));
                        drawAdditionalFigures();
                        resetNonMfcItemForm();
                    } else {
                        alert("Please enter a valid date in YYYY-MM format");
                    }
                } else {
                    alert("Please fill in all mandatory fields");
                }
            });
        }
    });

})();