User:Alien333/poemise.js

/* global mw,$ */ "use strict"; mw.loader.using(['mediawiki.util'], => { $( => { if (mw.config.get('wgCanonicalNamespace') == 'Page' && mw.config.get('wgPageContentModel') == 'proofread-page' && ['edit', 'submit'].includes(mw.config.get('wgAction'))) { var poemisebtn = mw.util.addPortletLink('p-tb', '#', 'Poemise', 'poemise-btn', 'Poemise.'); $(poemisebtn).click(event => { event.preventDefault; poemise }); } })}); var concat = (ll) => [].concat.apply([], ll); // merge array array var multiplyArray = (arr, length) => Array.from({ length }, => arr).flat; var ins = (s, c) => s.indexOf(c) != -1; var ind = (n) => ":".repeat(n); var pr = (s) => // Process Rhyme pattern (s=="")?[]: (ins(s, ";"))?concat(s.split(";").map(pr)): (ins(s, "*"))?multiplyArray(pr(s.split("*").slice(1).join("*")), Number(s.split("*")[0])): (ins(s, ","))?concat(s.split(",").map(pr)): (s[0]=="!")?[ind(Number(s.slice(1)))]: // multiple-digit indent (s[0]=="'")?pr(s.slice(1)+"*0;."): (s[0]==":")?pr(s.slice(1)+"*01;."): (s[0]==".")?["."].concat(pr(s.slice(1))): (s[0]=="[")?[s.match(/.*?\]/)[0].slice(1, -1)].concat(pr(s.match(/\].+/)[0].slice(1))): (/^[0-9]/.test(s))?[ind(Number(s[0]))].concat(pr(s.slice(1))):["!"]; function poemise { // apply poem formatting var [l, rhyme, ri] = [$('#wpTextbox1').val.split("\n"), [""], 0]; // list of lines, indent list, rhyme index var ei = l.findIndex((ll) => ll[0] == "-"); // end index ei = (ei != -1)?ei:l.length; var after = l.slice(ei).join("\n").slice(1); l = l.slice(0, ei); var si = l.findIndex((ll) => ll[0] == "+"); // start index si = (si != -1)?si:0; var before = l.slice(0, si).join("\n"); var anend = !l.some((ll) => ll[0] == "$" || (ll[1] == "$" && ll[0] == "+")); l = ("\n" + l.slice(si).join("\n") + "\n") .replace(/\n[+$]+/, "\n") .trim.split("\n"); l.forEach((ll) => {   	if (ll[0] == "*") {    		rhyme = pr(ll.slice(1).trim);    	} else if (ll[0] == "/") {    		ri = Number(ll.slice(1));    	}    }); l = l.filter((ll) => ll[0] != "/" && ll[0] != "*").join("\n").trim.split("\n"); if (rhyme.includes("!")) { alert("Poemise: Parsing error: unknown one-character pattern"); return; } else if (!rhyme.some((e) => e != ".")) { // would go into infinite loop else, which is a bit annoying alert("Poemise: Parsing error: the result indent pattern is only composed of stanza breaks"); return; }   before = (before)?before:(""); $('#wpTextbox1').val(before + "\n" + poem + after); doclean; }