MediaWiki:Gadget-checkBox.js

From Working With Glass
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
//This code was generated with Copilot.

$(function () {
    const $checklists = $("div.checklist");
    if (!$checklists.length) return;

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

    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();
    }

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

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

        const $labels = [];

        $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 $label = $('<label>')
                .css({ display: 'block', margin: '5px 0' })
                .append($checkbox)
                .append(" ")
                .append($li.contents());

            $labels.push($label);
        });

        $checklist.empty();

        $labels.forEach(label => $checklist.append(label));

        const resetLink = $('<a>')
            .text('Reset this checklist')
            .attr('href', '#')
            .addClass('noprint')
            .css({
                display: 'inline-block',
                marginTop: '8px',
                fontSize: '0.85em',
                color: '#0077cc',
                textDecoration: 'underline',
                cursor: 'pointer'
            })
            .on('click', function (e) {
                e.preventDefault();
                $checklist.find("input[type=checkbox]").each(function () {
                    $(this).prop("checked", false);
                });
                localStorage.removeItem(checklistKey);
            });

        $checklist.append(resetLink);
    });
});