User:Rummskartoffel/generate pings.js/sandbox.js

$( => {   const portlet_link = mw.util.addPortletLink("p-tb", "#", "Generate pings");    $(portlet_link).on("click",  => { const api = new mw.Api; api.get({           action: "query",            format: "json",            list: "categorymembers",            cmtitle: mw.config.get("wgPageName"),            cmnamespace: "2",            cmlimit: "100",            formatversion: "2",        }) .then(response =>           [...new Set(response.query.categorymembers .map(entry => entry.title.split("/")[0]) )]           .slice(0, 50)            .map(entry => `${entry}`)            .join(", ")        ) .then(wikitext => {           if (wikitext.length) {                try {                    navigator.clipboard.writeText(wikitext)                    .then( => mw.notify("Wikitext copied to clipboard"))                    .catch((...errors) => { console.warn("navigator.clipboard.writeText rejected with", ...errors); copy_to_clipboard_fallback(wikitext); });               } catch(error) {                    console.warn("error when accessing navigator.clipboard.writeText", error);                    copy_to_clipboard_fallback(wikitext);                }            } else {                mw.notify( "This category does not appear to contain any users. No wikitext was generated.", {type: "warn"} );           }        })        .catch((error_code, ...errors) => {            if (error_code === "invalidcategory") {                mw.notify( "Error: The current page does not appear to be a valid category, unable to generate pings.", {type: "error"} );           } else {                mw.notify("Error: An unknown error occured.", {type: "error"});                console.error(error_code, ...errors);            }        }); });

function copy_to_clipboard_fallback(wikitext) { const input = $(" ", {           value: wikitext,            type: "text",            style: "position: fixed; top: -100em; left: -100em;"        }).appendTo(document.body).select; document.execCommand("copy"); input.remove; mw.notify(           "Warning: Falling back to old method of clipboard access. Copying to clipboard may have failed.",            {type: "warn"}        ); } });