MediaWiki:CommentPreview/code.js

//preview button for article comments //todo: *? (function ($) {   var skeen = ['', 'oasis', 'monobook'].indexOf(skin);//1:oasis; 2:stereobook;    if (skeen < 1) return;//oasis&quadrobook only    var cp = {};//me    //create settings    window.fng = $.extend(true, {}, window.fng, {cp:cp});    cp = window.fng.cp;    //error on custom cp.lang with en=nil is intended by design    cp = $.extend(true, {}, cp, {lang: { en: {preview: 'Preview', cancel: 'Cancel', publish: 'Publish'}, be: {preview: 'Перадпрагляд', cancel: 'Скасаванне', publish: 'Захаваць'}, es: {preview: 'Vista previa', cancel: 'Cancelar', publish: 'Publicar'}, it: {preview: 'Anteprima', cancel: 'Annulla', publish: 'Pubblica'}, ru: {preview: 'Предпросмотр', cancel: 'Отмена', publish: 'Сохранить'}, uk: {preview: 'Попередній перегляд', cancel: 'Скасування', publish: 'Зберегти'}, "pt-br": {preview: 'Visualizar', cancel: 'Voltar', publish: 'Publicar'}, }});//not just $.extend(true, cp, ...). because of reasons.   var urlVars = $.getUrlVars;    cp.debug = cp.debug || urlVars.debug;    //throbber    var throbberSrc = null;

var log = cp.log = function { if (!cp.debug) return; log.meth = console.log; //console methods log.logs = log.logs || { 'debug': 'debug', 'error': 'error', 'info': 'info', 'log': 'log', 'warn': 'warn' };       log.a = [].slice.call(arguments); log.method = log.logs[(log.a[0] || '').toString.toLowerCase]; if (log.method) { log.a.splice(0, 1); log.meth = console[log.method]; }       log.a.unshift('cp'); log.meth.apply(this, log.a); };//log function chkThrobberSrc (src) { //is src belongs to wikia if (!src) return false; var url; try { url = new URL(src); return (/(\.wikia\.com|\.wikia\.nocookie\.net)$/.test(url.host)); }       catch (e) { return false; }       return false; }//chkthrobbersrc cp.rte2wiki = function (content) { //extract wikitext from rte-content var c = $(' ', {html: content}); c.find('[data-rte-meta]').replaceWith(function {            var $this = $(this);            var jstring = decodeURIComponent($(' ', {html: $this.data('rteMeta')}).text);            var jo = JSON.parse(jstring);            return jo.wikitext ? jo.wikitext : this;        });//replacewith return c.html; };//rte2wiki cp.getContent = function { //get *book content log('getcontent', this); return this.val; };//getcontent cp.onPreview = function (e) { //btnpreview click e.preventDefault; var MEW = $(e.target).closest('.article-comm-form');//('.MiniEditorWrapper'); if (!MEW) { log('onpreview mew not found for', e); return; }       var editor = MEW.find('.editarea textarea:first').data('wikiaEditor'); if (!editor) { log('onpreview editor not found for', e); //monobook presumed is           //wikiaeditor emulation mode on            editor = MEW.find('textarea:first'); editor.element = MEW; editor.mode = 'source'; editor.getContent = cp.getContent; }       cp.e = e;        cp.editor = editor; cp.throb(true); var content = editor.getContent; //nothing to parse if (!content || content.length < 1) { cp.throb(false); cp.onCancel; return; }       if (editor.mode === 'wysiwyg') { log('onpreview wysiwyg'); content = cp.rte2wiki(content); }//if wysiwyg var apiUri = (new mw.Uri({path: '/index.php'}).extend({action: 'ajax', rs: 'EditPageLayoutAjax', title: wgTitle, page: 'SpecialCustomEditPage', method: 'preview', content: content})); log('onpreview api', apiUri); $.getJSON(apiUri) .done(function (data) {           log('onpreview getjson.done', data);            cp.showPreview(data.html);        })//getjson.done .fail(function (data) {           log('onpreview getjson.fail', data);            cp.showPreview('Can\'t parse data. ' + data.responseText);       });//getjson.fail };//onpreview cp.onCancel = function (e) { //btncancel click. also, generic remove preview if (e && e.preventDefault) e.preventDefault; log('oncancel', e); //fire trigger to detach attached to previewed content stuff $(window).trigger('EditPagePreviewClosed'); $('.cp-modal').remove; $('body').removeClass('cp-blackout-body'); cp.editor = null; cp.e = null; $(document).off('keydown', cp.onkeydown); };//oncancel cp.onPublish = function (e) { //btnpublish click e.stopPropagation; log('onpublish', e); cp.editor.element.find('input[name=wpArticleSubmit]').click; cp.onCancel; };//onpublish cp.throb = function (state) { var $throbber, $closform = cp.editor ? $(cp.editor.element.context).closest('form') : {}; if ($closform.length) { $throbber = $closform.find('.throbber'); if (!$throbber.length) return; $throbber.css('visibility', state ? 'visible' : 'hidden'); }//if editor<-form };//throb cp.onkeydown = function (e) { //keydown handler. and mouse if ($(e.target).closest('.cp-window').length) return; if (e.keyCode === 27 || e.button !== undefined) cp.onCancel; };//onkeydown cp.disablePreview = function (target) { //disable preview button if (!target) return; if (!(target instanceof jQuery)) target = $(target); var btnpreview = target.closest('.article-comments').find('.buttons .cp-button-preview'); if (!btnpreview.length) return; btnpreview.attr('disabled', 'disabled'); };//disablepreview cp.enablePreview = function (target) { //enable preview button if (!target) return; if (!(target instanceof jQuery)) target = $(target); var btnpreview = target.closest('.article-comments').find('.buttons .cp-button-preview'); if (!btnpreview.length) return; btnpreview.removeAttr('disabled'); };//enablepreview cp.addButtons = function (content) { log('addbuttons', content); if (!(content instanceof jQuery)) content = $(content); var buttons = content.find('>:not(#article-comments-ul) .buttons'); if (!buttons.length) return; buttons.find('.cp-button').remove; buttons.append(cp.btnPreview.clone); //change throbber var $throbber = buttons.find('.throbber'); if (throbberSrc && $throbber.attr('src') !== throbberSrc) $throbber.attr('src', throbberSrc); };//addbuttons cp.mo = new MutationObserver(function (records, obj) {       //mutation observer callback        $.each(records, function  { if (!this.addedNodes) return true; var arr = [].slice.call(this.addedNodes); log('debug', 'mo.arr', arr); arr.map(function (v) {               var $this = $(v);                log('debug', 'mo.map', $this);                if ($this.hasClass('article-comments') || $this.hasClass('article-comm-edit-box')) {                    cp.addButtons($this);                }//if article-comments            });//map });//each record   });//mutation observer cp.init = function { log('init');

if (cp.clang) { log('warn', 'init 2nd init detected'); return; }       //is there smth to do        if (!$('#WikiaArticleComments').length) { log('init no comments found'); return; }       //user-defined throbber throbberSrc = chkThrobberSrc(cp.throbber) ? cp.throbber : null; //build gui //current lang cp.clang = cp.lang[urlVars.uselang || cp.uselang] || cp.lang[wgContentLanguage] || cp.lang.en; cp.btnPreviewText = cp.clang.preview || (cp.lang[wgContentLanguage] || cp.lang.en).preview; cp.btnCancelText = cp.clang.cancel || (cp.lang[wgContentLanguage] || cp.lang.en).cancel; cp.btnPublishText = cp.clang.publish || (cp.lang[wgContentLanguage] || cp.lang.en).publish; var isDark = $('body').hasClass('oasis-dark-theme'); //dark/light theme-specific styling var dlStyle = { dark: 'background-color:rgba(200,200,200,0.3);', light: 'background-color:rgba(200,200,200,0.85);' };       //dark for dark oasis, light for others dlStyle.current = isDark && skeen === 1 ? dlStyle.dark : dlStyle.light; cp.modal = $(' ', {           class: 'cp-modal cp-blackout-modal'            ,style: 'z-index:10000;position:absolute;left:0;top:0;width:100%;height:100%;background-color:rgba(0,0,0,0.8);'        }); cp.window = $(' ', {           class: 'cp-window'            ,style: dlStyle.current + 'z-index:1000;position:absolute;width:700px;height:400px;overflow:visible;padding:5px 20px;'        }); cp.content = $(' ', {           class: 'cp-content'            //,id: 'mw-content-text'            ,style: 'overflow:auto;margin:5px;border-style:groove;border-width:thin;border-color:silver;height:300px;max-height:350px;'        }); cp.header = $(' ', {           class: 'cp-header'            ,style: 'left:0;right:0;top:0;margin:5px;line-height:2em;'        }); cp.footer = $(' ', {           class: 'cp-footer'            ,style: 'left:0;right:0;bottom:0;padding-bottom:15px;padding-right:20px;position:absolute;'        }); cp.btnPreview = $(' ', {           class: 'cp-button cp-button-preview wikia-button secondary',            type: 'button',            value: cp.btnPreviewText            ,style: 'float:right;'        }); cp.btnCancel = $(' ', {           class: 'cp-button cp-button-cancel wikia-button secondary',            type: 'button',            value: cp.btnCancelText            ,style: 'float:right;margin-right:7px;'        }); cp.btnPublish = $(' ', {           class: 'cp-button cp-button-publish wikia-button',            type: 'button',            value: cp.btnPublishText            ,style: 'float:right;'        }); cp.xcancel = $('', {           class: 'cp-xcancel',            href: '#',            text: 'X'            ,style: 'float:right;font-weight:500;font-size:x-large;'        });

cp.header.append(cp.xcancel).append($(' ', {text: cp.btnPreviewText})); cp.footer.append(cp.btnPublish).append(cp.btnCancel); cp.window.append(cp.header) .append(cp.content) .append(cp.footer); cp.modal.append(cp.window); //events $('body').on('click', '.cp-button-preview', cp.onPreview); $('body').on('click', '.cp-button-cancel, .cp-xcancel', cp.onCancel); //$('body').on('click', '.cp-xcancel', cp.onCancel); $('body').on('click', '.cp-button-publish', cp.onPublish); $('body').on('click', '.cp-modal', cp.onkeydown); //add hook var hcb = function(content) { //add preview button to new-article-comment if (!$(content).hasClass('article-comments')) return; mw.hook('wikipage.content').remove(hcb); cp.addButtons(content); //set observer to add buttons to all mew's           if (content instanceof jQuery) content = content.get(0); log('init.wikipage.content', content); cp.mo.observe(content, {childList: true, subtree: true}); };//hcb //remove body y-scroll only if space is enough mw.util.addCSS('@media only screen and (min-height:500px) {.cp-blackout-body {overflow-y:hidden;} .cp-blackout-modal{overflow-y:scroll;}'); mw.hook('wikipage.content').add(hcb); window.fng.cp = cp;//$.extend(window.fng.cp, cp); };//init cp.showPreview = function (content) { log('showpreview content:', content); cp.modal.find('.cp-content').html(content); //remove title cp.modal.find('.cp-content .pagetitle:first').css('display', 'none');

//.prepend to "fix" gallery-slider searching for id       //slider fix. change ids to supposed-to-be-unique, then re-init slider var slider = cp.modal.find('.wikiaPhotoGallery-slider-body'); var slides, id, ids = []; $.each(slider, function {            id = '10000' + this.id.replace(/(wikiaPhotoGallery\-slider\-body\-)(\d)/, '$2');            this.id = 'wikiaPhotoGallery-slider-body-' + id;            ids.push(id);            slides = $(this).find('[class*="wikiaPhotoGallery-slider-"]');            $.each(slides, function  { this.id = this.id.replace(/(wikiaPhotoGallery\-slider\-)(\d)-(\d)/, '$1' + id + '-$3'); });//each slides       });//each slider $('body').addClass('cp-blackout-body'); cp.throb(false); $('body').prepend(cp.modal); cp.modal.find('.cp-window').css({           left: (window.innerWidth > cp.window.width ? window.innerWidth / 2 - cp.window.width / 2 : 0) + $('body').scrollLeft,           top: (window.innerHeight > cp.window.height ? window.innerHeight / 2 - cp.window.height / 2 : 50) + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop)       }); //enlarge modal: *book fix // units are for losers if (cp.modal.height < $('body').height) { cp.modal.height($('body').height); cp.modal.css('height', height($('body').height)); }       if (cp.modal.width < window.innerWidth) { cp.modal.width(window.innerWidth); cp.modal.css('width', window.innerWidth); }       $(document).on('keydown', cp.onkeydown);//doc.keydown mw.hook('wikipage.content').fire($('.cp-modal')); //init sliders for (var i = 0; i < ids.length; i++) { //avoid weird circumstances with lost slider environment if (window.WikiaPhotoGallerySlider && window.WikiaPhotoGallerySlider.init) window.WikiaPhotoGallerySlider.init(ids[i]); }//for ids };//showPreview //doc.rdy $(cp.init); }(jQuery));