MediaWiki:Gadget-checkBox.js: Difference between revisions

From Working With Glass
Jump to navigation Jump to search
Code side of attempt to add saving checklist capabilities.
 
Oops, I set it up wrong. Fixed to look for div.
Line 2: Line 2:


$(function () {
$(function () {
     const $checklists = $("ul.checklist");
     const $checklists = $("div.checklist");
     if (!$checklists.length) return; // Exit early if no checklist found
     if (!$checklists.length) return; // Exit early if no checklist found



Revision as of 09:31, 15 October 2025

//This code was generated with Copilot.

$(function () {
    const $checklists = $("div.checklist");
    if (!$checklists.length) return; // Exit early if no checklist found

    const pageKey = mw.config.get('wgPageName') || 'defaultChecklist';

    // Simple hash function for strings
    function hashString(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            hash = ((hash << 5) - hash) + str.charCodeAt(i);
            hash |= 0;
        }
        return hash.toString();
    }

    // Process each checklist separately
    $checklists.each(function (listIndex) {
        const $checklist = $(this);
        const checklistKey = `${pageKey}-checklist-${listIndex}`;
        let savedState = {};

        try {
            savedState = JSON.parse(localStorage.getItem(checklistKey)) || {};
        } catch (e) {
            savedState = {};
        }

        $checklist.find("li").each(function () {
            const $li = $(this);
            const rawText = $li.text().trim();
            const itemId = hashString(rawText);
            const isChecked = savedState[itemId] === true;

            const $checkbox = $('<input type="checkbox">')
                .prop("checked", isChecked)
                .on("change", function () {
                    savedState[itemId] = $(this).prop("checked");
                    localStorage.setItem(checklistKey, JSON.stringify(savedState));
                });

            const labelContent = $('<label>').append($checkbox).append(" ").append($li.contents());
            $li.empty().append(labelContent);
        });

        const resetButton = $('<button>')
            .text('Reset This Checklist')
            .css({ margin: '10px 0', display: 'block' })
            .on('click', function () {
                $checklist.find("li input[type=checkbox]").each(function () {
                    $(this).prop("checked", false);
                });
                localStorage.removeItem(checklistKey);
            });

        $checklist.before(resetButton);
    });
});