MediaWiki:Papi.js

// param api. // simple way to parse text for params, then change and save them /* usage: .load(title) params = .parse(text) params[i].value = new_value .save(.make(params)) !function { var p = {}; window.papi = p;   p.debug = $.getUrlVar('debug'); p.r = {}; p.r.param = /(\{{3}([^|}]+)(\|?)([^}]*)(\}\}\}+))/gm; p.data = ''; p.title = '';

// log p.log = function { if (!p.debug) return; var a = [].slice.call(arguments); a.unshift('papi'); return console.log.apply(this, a); };// log

// creates from param // returns string p.createParam = function (param) { return '{{{' + param.name + param.delim + (param.value || '') + param.ending; };// createParam

// replaces params in data by params from params // returns string p.make = function (params, data) { if (!params) return; var s = data || p.data; params.forEach(function (param, i) {           p.log('make', i, p.createParam(param));            s = s.replace(new RegExp($.escapeRE(param.full), 'g'), p.createParam(param));        }); return s;   };// make

// parses data for params // returns array of {full, name, delim, value, ending} p.parse = function (data) { var param, params = []; while (param = p.r.param.exec(data)) { param = { full: param[1],// full param, as is               name: param[2],// param name delim: param[3],// delim (|), if any value: param[4],// param value ending: param[5],// closing brackets };           params.push(param); }       p.log(params); return params; };// parse

// load data from title // returns promise; resolve(string) p.load = function (title) { var d = $.Deferred; p.data = ''; p.title = ''; $.get('/index.php', {action: 'raw', title: title}) .done(function(data) {           if (!data || data.error) {                d.reject(data);            }            p.data = data;            p.title = title;            d.resolve(p.parse(data));        })// done .fail(function(data) {           d.reject(data);        }); return d.promise; };// load

// saves data to [title] // title by default: last .load'ed   // returns promise p.save = function (data, title) { var d = $.Deferred; title = title || p.title; if (!title) { p.log('save', 'no title supplied'); return d.reject('no title supplied'); }       var s = data || p.data; if (!s || !s.trim) { p.log('save', 'no data supplied'); return d.reject('no data supplied'); }       $.post('/api.php', {            action: 'edit',            title: title,            text: s,            summary: 'papi edit',            token: mw.user.tokens.values.editToken,        }) .done(function(data) {           p.log('save', 'done');            return d.resolve(data);        }) .fail(function(data) {           p.log('save', 'fail', data);            return d.reject(data);        }); return d.promise; };// save

mw.hook('papi.ready').fire(p); };