Difference between revisions of "MediaWiki:Common.js"

From cm2.liecourt.com
(Fill database)
(No difference)

Revision as of 12:39, 25 May 2020

/* Any JavaScript here will be loaded for all users on every page load. */

$( document ).ready(function() {

	
if ($('.WSShowOnSelect') ) {
		WsShowOnSelect();
}

$('body.action-edit #wpTextbox1, body.action-submit #wpTextbox1').keydown(function(event)  {
    var x = event.keyCode;
    if (x == 13 ) {
        if(!event.shiftKey){
           var insert =  document.execCommand('insertText', false, '<!-- \n -->');
           if(insert){
               event.preventDefault();
                $('#wpTextbox1').focus()
                insert
            }
        }
    }
})




// Start of esc save
	
	
	
  $('body.action-edit, body.action-submit').keydown(function()  {
    var x = event.keyCode;
    if (x == 27) {
      $.ajax({
        url :'/api.php?action=query&meta=tokens&format=json',
        type: 'GET',
        dataType: 'json',
        success : function(result){
          var token = result.query.tokens.csrftoken;

          $("input[name='wpEditToken']").attr("value", token );

          saveEdit();

        }
      });
    }else{
      mw.confirmCloseWindow();
      $('#wpSave, #wpPreview, #wpDiff').on('click', function(){
        $( window ).off( 'beforeunload' );
      })
    }

  })

if($('body').hasClass('action-submit')){
  $('#top').prepend('<button class="btn btn-success enable-live-mode">Enable live mode</button>');
  $(document).on('click','.enable-live-mode', function(){
    if($(this).hasClass('btn-success')){
     liveMode();
     $(this).removeClass('btn-success');
     $(this).text('Live mode is on');
   }else{
      $(this).addClass('btn-success');
      $('body.action-submit textarea').off("change keyup paste");
      $(this).text('Enable live mode');
   }

  });
}
});

window.saveEdit = function() {
  $.ajax({
    url : $('form.mw-editform').attr('action'),
    type : 'POST',
    data :$('form.mw-editform').serialize(),
    success : function(html) {
     $( window ).off( 'beforeunload' );
      mw.notify( 'Saved' );
      if($('body').hasClass('action-submit')){
       var parser = new DOMParser();
       var doc = parser.parseFromString(html, "text/html");
       var elem = doc.querySelectorAll('.mw-content-ltr')[0];
      $('.mw-content-ltr').html(elem);
      }
    }
  })
}; 

window.liveMode = function() {
  var oldVal = "";
  $('body.action-submit textarea').on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    var text = encodeURIComponent($('textarea').val());
    
    $.ajax({
      url: '/api.php?action=parse&format=json&formatversion=2&title=New&text='+text+'&pst=&prop=text%7Cmodules%7Cjsconfigvars&preview=true&disableeditsection=true&uselang=en',
      dataType: 'json',
      success: function (x) {
        $('#wikiPreview').html(x.parse.text);
      } 
    });
  });
};
/* End of Esc Save */


/***** WSForm: loading Select2 ****/
$( document ).ready(function() {
  if ($('select[data-inputtype="ws-select2"]')[0]) {
    mw.loader.load('/extensions/WSForm/select2.min.css', 'text/css');
    $.getScript('/extensions/WSForm/select2.min.js').done(function() {
      $('select[data-inputtype="ws-select2"]').each(function() {
        var selectid = $(this).attr('id');
        var selectoptionsid = 'select2options-' + selectid;
        var select2config = $("input#" + selectoptionsid).val();
        var F = new Function(select2config);
        return (F());
      });
    });
  }
});
/* End of WSForm: Select2 */

(function($) {
    $.fn.autogrow = function() {
        return this.each(function() {
            var textarea = this;
            $.fn.autogrow.resize(textarea);
            $(textarea).focus(function() {
                textarea.interval = setInterval(function() {
                    $.fn.autogrow.resize(textarea);
                }, 500);
            }).blur(function() {
                clearInterval(textarea.interval);
            });
        });
    };
    $.fn.autogrow.resize = function(textarea) {
        var lineHeight = parseInt($(textarea).css('line-height'), 10);
        var lines = textarea.value.split('\n');
        var columns = textarea.cols;
        var lineCount = 0;
        $.each(lines, function() {
            lineCount += Math.ceil(this.length / columns) || 1;
        });
        var height = lineHeight * (lineCount + 1);
        $(textarea).css('height', height);
    };
})(jQuery);

$('textarea.form-control').autogrow();


/* WSSHOWONSELECT */
/**
 * applying show on select on the page and make sure everyting will be handled as needed
 */
function WsShowOnSelect() {
    var selectArray = [];
    $('.WSShowOnSelect').find('[data-wssos-show]').each(function (index, elm) {
        if ( $(elm).is('option') ) {
            var isInArray = false;
            var selectParent = $(elm).parent()[0];
            for ( var i = 0; i < selectArray.length; i++ ) {
                if ( $(selectParent).is($(selectArray[i])) ) {
                    isInArray = true;
                }
            }
            if ( !isInArray ) {
                selectArray.push(selectParent);
                handleSelect(selectParent);
            }
        } else if ( $(elm).is('input[type=radio]') ) {
            handleRadio(elm);
        } else if ( $(elm).is('input[type=checkbox]') ) {
            handleCheckbox(elm);
        } else if ( $(elm).is('button') ) {
            handleButton(elm);
        }
    });
}

/**
 * handle the radio button changes, show what is needed
 * @param radioElm
 */
function handleRadio(radioElm) {
    var pre_wssos_value = $(radioElm).data('wssos-show');
    var pre_parent_wssos = $(radioElm).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    if ( $(radioElm).parent().hasClass('WSShowOnSelect') ) {
        pre_parent_wssos = $(radioElm).parent()[0];
        pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    }
    if ( radioElm.checked ) {
        $(pre_wssos_elm).removeClass('hidden');
        putAllTypesDataInName(pre_wssos_elm);
    } else {
        putAllTypesNameInData(pre_wssos_elm);
    }
    $(pre_parent_wssos).find('input[type=radio][name="'+ radioElm.name +'"]').on('change', function () {
       var wssos_value = $(this).data('wssos-show');
       var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( $(this).parent().hasClass('WSShowOnSelect') ) {
            parent_wssos = $(this).parent()[0];
            wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        }
       $(parent_wssos).find('input[name="'+this.name+'"][type="radio"]').each(function(index, radiobtn) {
          var radio_hide_data_attr = $(radiobtn).data('wssos-show');
           $(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]').addClass('hidden');
           putAllTypesNameInData($(parent_wssos).find('[data-wssos-value="'+radio_hide_data_attr+'"]'));
       });

       if ( this.checked ) {
           wssos_elm.removeClass('hidden');
           putAllTypesDataInName(wssos_elm);
       } else {
           wssos_elm.addClass('hidden');
           putAllTypesNameInData(wssos_elm);
       }
    });
}

/**
 * handle the checkbox changes, show what is needed
 * @param checkElm
 */
function handleCheckbox(checkElm) {
    var pre_wssos_value = $(checkElm).data('wssos-show');
    var pre_parent_wssos = $(checkElm).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    if ( $(checkElm).parent().hasClass('WSShowOnSelect') ) {
        pre_parent_wssos = $(checkElm).parent()[0];
        pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');
    }
    if ( checkElm.checked ) {
        pre_wssos_elm.removeClass('hidden');
        // set the dataset value of data-name-attribute back in the name attribute
        putAllTypesDataInName(pre_wssos_elm);

        // set the name value of the unchecked element in the value of data-name-attribute and remove the name attribute
        if ( $(checkElm).has('data-wssos-show-unchecked') ) {
            var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked');
            var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]');
            putAllTypesNameInData(pre_unchecked_elm);
        }
    } else {
        // set data-name-attribute to the value of name attribute and remove the name attribute
        putAllTypesNameInData(pre_wssos_elm);

        if ( $(checkElm).has('data-wssos-show-unchecked') ) {
            var pre_unchecked_value = $(checkElm).data('wssos-show-unchecked');
            var pre_unchecked_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_unchecked_value+'"]');
            $(pre_unchecked_elm).removeClass('hidden');
            // set the name attribute to the value of data-name-attribute
            putAllTypesDataInName(pre_unchecked_elm);
        }
    }
    $(checkElm).on('change', function(e) {
        e.stopPropagation();
       var wssos_value = $(this).data('wssos-show');
       var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
       var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( $(this).parent().hasClass('WSShowOnSelect') ) {
            parent_wssos = $(this).parent()[0];
            wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        }
        if ( this.checked ) {
            wssos_elm.removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        } else {
            wssos_elm.addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        }

        if ( $(this).has('data-wssos-show-unchecked') ) {
            var wssos_unchecked_value = $(this).data('wssos-show-unchecked');
            var wssos_unchecked_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_unchecked_value+'"]');
            if ( this.checked ) {
                wssos_unchecked_elm.addClass('hidden');
                putAllTypesNameInData(wssos_unchecked_elm);
            } else {
                wssos_unchecked_elm.removeClass('hidden');
                putAllTypesDataInName(wssos_unchecked_elm);
            }
        }
    });
}


/**
 * handle the select box changes to show what is needed on select
 * @param selectElm
 */
function handleSelect(selectElm) {
    var selectVal = $(selectElm).val();
    $(selectElm).children().each(function (index, option) {
        var wssos_value = $(option).data('wssos-show');
        var parent_wssos = $(option).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
        if ( option.selected || $(option).val() === selectVal) {
            wssos_elm.removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        } else {
            wssos_elm.addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        }
    });

    $(selectElm).on('change', function () {
        $(this).children().each(function (index, option) {
            var wssos_value = $(option).data('wssos-show');
            var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
            var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');
            if ( option.selected ) {
                wssos_elm.removeClass('hidden');
                putAllTypesDataInName(wssos_elm);
            } else {
                wssos_elm.addClass('hidden');
                putAllTypesNameInData(wssos_elm);
            }
        });
    });
}

function handleButton(btnElm) {
    var pre_wssos_value = $(this).data('wssos-show');
    var pre_parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
    var pre_wssos_elm = $(pre_parent_wssos).find('[data-wssos-value="'+pre_wssos_value+'"]');

    // set up the start and make sure the element is hidden
    $(pre_wssos_elm).addClass('hidden');
    putAllTypesNameInData(pre_wssos_elm);
    // add on click listener to the button
    $(btnElm).on('click', function(e) {
        var wssos_value = $(this).data('wssos-show');
        var parent_wssos = $(this).parentsUntil('.WSShowOnSelect').parent()[0];
        var wssos_elm = $(parent_wssos).find('[data-wssos-value="'+wssos_value+'"]');

        // possibility to hide the wanted element back if an option
        if ( !$(wssos_elm).hasClass('hidden') ) {
            $(wssos_elm).addClass('hidden');
            putAllTypesNameInData(wssos_elm);
        } else {
            $(wssos_elm).removeClass('hidden');
            putAllTypesDataInName(wssos_elm);
        }
    });
}

/**
 * find all different types which name attribute should go to the dataset
 * @param elm
 */
function putAllTypesNameInData(elm) {
    putNameAttrValueInDataset($(elm).find('input,select,textarea'));
    putRequiredInDataset($(elm).find('input,select,textarea'));
}


/**
 * find all different types which data-attribute should go to the name-attribute
 * @param elm
 */
function putAllTypesDataInName(elm) {
    putDatasetValueBackInName($(elm).find('input,select,textarea'));
    putDatasetInRequired($(elm).find('input,select,textarea'));
}

/**
 * set the name attribute value to the dataset data-name-attribute, remove the name attribute
 * @param elm
 */
function putNameAttrValueInDataset($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).attr('name') !== '' ) {
            var name = $(elm).attr('name');
            if (name) {
                $(elm).attr('data-name-attribute', name);
                $(elm).removeAttr('name');
            }
        }
    });
}


/**
 * set the name attribute to the value of the data-name-attribute
 * @param elm
 */
function putDatasetValueBackInName($elm) {
    $.each($elm, function(index, elm) {
        if ( $(elm).attr('data-name-attribute') !== '' ) {
            var datasetName = $(elm).data('name-attribute');
            if (datasetName) {
                $(elm).attr('name', datasetName);
            }
        }
    });
}

/**
 * set the required attr in the dataset data-ws-required
 * @param $elm
 */
function putRequiredInDataset($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).is(':required') ) {
            $(elm).attr('data-ws-required', true);
            $(elm).prop('required', false);
        }
    });
}

/**
 * if the element has data-ws-required the make the element required
 * @param $elm
 */
function putDatasetInRequired($elm) {
    $.each($elm, function (index, elm) {
        if ( $(elm).data('ws-required') ) {
            $(elm).prop('required', true);
        }
    })
}

/* END OF WSSHOWONSELECT */