MediaWiki:OnlyIfFormEditing.js

Материал из свободной русской энциклопедии «Традиция»
Перейти к навигации Перейти к поиску

Замечание: Чтобы после сохранения вступили в силу изменения стилей, перезагрузите файл //traditio.wiki/w/load.php?debug=false&lang=ru&modules=site&only=styles&skin=vector&*, если используете скин Vector, или //traditio.wiki/w/load.php?debug=false&lang=ru&modules=site&only=styles&skin=common&*, если используете скин Common.

Чтобы вступили в силу изменения скриптов, перезагрузите файл //traditio.wiki/w/load.php?debug=false&lang=ru&modules=site&only=scripts&skin=vector&*, если используете скин Vector, или //traditio.wiki/w/load.php?debug=false&lang=ru&modules=site&only=scripts&skin=common&*, если используете скин Common.

Гаджеты и импортируемые скрипты загружаются отдельными файлами.

// <source lang="JavaScript">
/* Скрипты, нужные для редактирования с помощью форм:
</source>
==== Панель вставки символов ====
<source lang="JavaScript">
*/
// Edit Tools loader:
//Prevent the static edittools from flashing before the compact edittools below is loaded.
appendCSS('div.edittools-text { display:none; }');

$(function () {
   // needs to be deferred until the DOM has fully loaded
   var last_elem = document.getElementById("wpDiff");
   var placeholder = document.createElement ('div');
   placeholder.id = 'editpage-specialchars';
   last_elem.parentNode.appendChild (placeholder);
   if (!placeholder || window.noDefaultEdittools) {
     //Show the static edittools again for users with "window.noDefaultEdittools=true".
     appendCSS('div.edittools-text { display:block; }');
     return;
   }
   var match = /(?:^| )edittools-version-(\d+)(?: |$)/.exec(placeholder.className);
 
   // set window.testJsEdittools = true to enable testing before full deployment
   if (!match && window.testJsEdittools)
       match = /(?:^| )edittools-version-(test\d+)(?: |$)/.exec(placeholder.className);
 
   if (!match) return;
   var url = wgScript + '?title=MediaWiki:Edittools.js&action=raw&ctype=text/javascript&nocache=' + match[1];
   importScriptURI(url);
}); /*
</source>
==== Дополнительные кнопки на панель инструментов ====
<source lang="JavaScript">
*/
// Import edit.js:
var scriptElem = document.createElement ('script');
scriptElem.setAttribute ('src', wgScriptPath + '/skins/common/edit.js');
scriptElem.setAttribute ('type' ,'text/javascript');
document.getElementsByTagName ('head')[0].appendChild (scriptElem);

// Викификатор:
importScript ("MediaWiki:Wikificator.js");

//============================================================
// Extra toolbar options
//============================================================
//********WRITTEN BY User:MarkS********
//This is a modified copy of a script by User:MarkS for extra features added by User:Voice of All.


//============================================================
// Table generator
//============================================================
 
/**
 *
 * English: Generate an array using Mediawiki syntax
 *
 * @author: fr:user:dake (language conversion and  new options added by en:user:Voice of All)
 * @version: 0.1
 */
 
function generateTableau(nbCol, nbRow, border, styleHeader, styleLine, exfield, align, padding, textbox_id)
{
        var code = "\n";
 
        if (padding==false) padding=0;
        else if (padding==true) padding=1;
 
        code += '{| align="' + align + '" class="standard"\n';
        code += '|+\n';
 
        for (var i=1;i<nbCol+1;i++) code += '! |Столбец ' + i + '\n';
 
        var items = 0;
        for (var j=0;j<nbRow;j++) {
                code += '|-----\n'
 
                for (var i=0;i<nbCol;i++) code += '| ячейка\n';
        }
 
        code += '|+\n';
        code += '|}\n';
        insertTags('','', code, document.getElementById (textbox_id)); 
}
 
/**
 *
 * English: Open a popup with parameters to generate an array. 
 * The number of rows/columns can be modified. Some additional
 * parameters are related to templates available on :fr
 *
 * @author: fr:user:dake
 * @version: 0.1
 */
 
function popupTable (textbox)
{
  var popup = window.open('','name','height=180,width=300,scrollbars=yes');
 
  javaCode =  '<script type="text\/javascript">function insertCode (textbox_id){';
  javaCode += 'var row = parseInt(document.paramForm.inputRow.value); '
  javaCode += 'var col = parseInt(document.paramForm.inputCol.value); '
  javaCode += 'var bord = 0; '
  javaCode += 'var styleHeader = false; '
  javaCode += 'var styleLine = false; '
  javaCode += 'var exfield = false; '
  javaCode += 'var align = document.paramForm.inputAlign.value; '
  javaCode += 'var padding = false; '
  javaCode += 'window.opener.generateTableau(col,row,bord,styleHeader,styleLine,exfield,align,padding, textbox_id); '
  javaCode += "alert('Таблица создана!'); "
  javaCode += 'window.close(); '
  javaCode += '}<\/script>';
 
  popup.document.write('<html><head><title>Создание таблицы</title>');
  popup.document.write('<script type="text\/javascript" src="\/w\/skins\/common\/wikibits.js"><!-- wikibits js --><\/script>');
  popup.document.write('<style type="text\/css" media="screen,projection">/*<![CDATA[*/ @import "\/skins-1.5\/monobook\/main.css?5"; /*]]>*/<\/style>');
  popup.document.write(javaCode); 
  popup.document.write('</head><body>');
  popup.document.write('<p>Введите параметры таблицы: </p>');
  popup.document.write('<form name="paramForm">');
  popup.document.write('Выравнивание: <input type="text" name="inputAlign" value="center" ><p>');
  popup.document.write('Количество строк: <input type="text" name="inputRow" value="3" ><p>');
  popup.document.write('Количество столбцов: <input type="text" name="inputCol" value="3" ><p>');
  popup.document.write('</form">');
  popup.document.write('<p><a href="javascript:insertCode (\'' + textbox.id + '\')"> Вставить таблицу</a>     |');
  popup.document.write('    <a href="javascript:self.close()">Отмена (закрыть окно)</a></p>');
  popup.document.write('</body></html>');
  popup.document.close();
}

// This is based on the original code on Wikipedia:Tools/Editing tools

function InsertButtonsIntoToolBarInForm() {
// Alexander Mashin, Oct 2nd, 2009:
// дублирование кнопок для formedit:

    $("textarea").each (function () {
    
        var mwStandardEditButtons = new Array ();

        // Генератор таблиц:
        mwStandardEditButtons [mwStandardEditButtons.length] = {
            "imageFile": 'http://upload.wikimedia.org/wikipedia/commons/0/04/Button_array.png',
            "speedTip" : 'Создать таблицу',
            "fn"       : function (textbox) {popupTable (textbox); return false; }
        };

        // Викификатор:
        mwStandardEditButtons [mwStandardEditButtons.length] = {
            "width"    : 65,
            "imageFile": 'http://upload.wikimedia.org/wikisource/ru/d/d1/Button-wikifikator.png',
            "speedTip" : 'Викификатор',
            "fn"       : function (textbox) {Wikify (textbox); return false; }
        };

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/cyrl/button_bold.png",
        "speedTip":"Полужирное начертание",
        "tagOpen":"\'\'\'",
        "tagClose":"\'\'\'",
        "sampleText":"Полужирное начертание"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/cyrl/button_italic.png",
        "speedTip":"Курсивное начертание",
        "tagOpen":"\'\'",
        "tagClose":"\'\'",
        "sampleText":"текст курсивом"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {"imageFile": "/w/skins/common/images/cyrl/button_link.png",
        "speedTip":"Внутренняя ссылка",
        "tagOpen":"[[",
        "tagClose":"]]",
        "sampleText":"Статья"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_extlink.png",
        "speedTip":"Внешняя ссылка (помните о префиксе http:// )",
        "tagOpen":"[",
        "tagClose":"]",
        "sampleText":"http://(адрес)"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_headline.png",
        "speedTip":"Заголовок 2-го уровня",
        "tagOpen":"\n== ",
        "tagClose":" ==\n",
        "sampleText":"Заголовок"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_image.png",
        "speedTip":"Встроенный файл",
        "tagOpen":"[[Файл:",
        "tagClose":"]]",
        "sampleText":"(рисунок.png"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_media.png",
        "speedTip":"Ссылка на медиа-файл",
        "tagOpen":"[[Медиа:",
        "tagClose":"]]",
        "sampleText":"медиа.ogg"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_math.png",
        "speedTip":"Математическая формула (формат LaTeX)",
        "tagOpen":"\x3cmath\x3e",
        "tagClose":"\x3c/math\x3e",
        "sampleText":"(формула)"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_nowiki.png",
        "speedTip":"Игнорировать вики-форматирование",
        "tagOpen":"\x3cnowiki\x3e",
        "tagClose":"\x3c/nowiki\x3e",
        "sampleText":"(код без форматирования)"};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_sig.png",
        "speedTip":"Ваша подпись и момент времени",
        "tagOpen":"--~~~~",
        "tagClose":"",
        "sampleText":""};

        mwStandardEditButtons [mwStandardEditButtons.length] = {
        "imageFile": "/w/skins/common/images/button_hr.png",
        "speedTip":"Горизонтальная линия (не используйте часто)",
        "tagOpen":"\n----\n",
        "tagClose":"",
        "sampleText":""};

        mwCustomEditButtons = mwStandardEditButtons.concat (mwCustomEditButtons);
        
        // Alexander Mashin, October 2nd, 2009. Draw the toolbar when editing with a form:
        var toolbar = document.createElement ('span');
        toolbar.id = 'toolbar';

        for (var i = 0; i < mwCustomEditButtons.length; i++) {
            addButton2Toolbar (toolbar, mwCustomEditButtons [i], this);
        }    
        this.parentNode.insertBefore (toolbar, this);
    });
} 
 
function addButton2Toolbar (toolbar, button, textbox) {
    var img     = document.createElement ('img');
    img.class   = 'mw-toolbar-editbutton';
    img.width   = undefined !== button.width ? button.width : 23;
    img.height  = 22;
    img.src     = button.imageFile;
    img.border  = 0;
    img.alt     = button.speedTip;
    img.title   = button.speedTip;
    img.style.cursor
                = 'pointer';
    img.onclick = undefined !== button.fn
        ? function () {
              button.fn (textbox);
              return false;
          }
        : function() {
	      insertTags2Textbox (button.tagOpen, button.tagClose, button.sampleText, textbox);
	      return false;
   	  };
    toolbar.appendChild (img);
}

// apply tagOpen/tagClose to selection in textarea,
// use sampleText instead of selection if there is none
function insertTags2Textbox (tagOpen, tagClose, sampleText, txtarea) {
	var selText, isSample = false;

	if (document.selection  && document.selection.createRange) { // IE/Opera

		//save window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			var winScroll = document.documentElement.scrollTop
		else if (document.body)
			var winScroll = document.body.scrollTop;
		//get current selection  
		txtarea.focus();
		var range = document.selection.createRange();
		selText = range.text;
		//insert tags
		checkSelectedText();
		range.text = tagOpen + selText + tagClose;
		//mark sample text as selected
		if (isSample && range.moveStart) {
			if (window.opera)
				tagClose = tagClose.replace(/\n/g,'');
			range.moveStart('character', - tagClose.length - selText.length); 
			range.moveEnd('character', - tagClose.length); 
		}
		range.select();   
		//restore window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			document.documentElement.scrollTop = winScroll
		else if (document.body)
			document.body.scrollTop = winScroll;

	} else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla

		//save textarea scroll position
		var textScroll = txtarea.scrollTop;
		//get current selection
		txtarea.focus();
		var startPos = txtarea.selectionStart;
		var endPos = txtarea.selectionEnd;
		selText = txtarea.value.substring(startPos, endPos);
		//insert tags
		checkSelectedText();
		txtarea.value = txtarea.value.substring(0, startPos)
			+ tagOpen + selText + tagClose
			+ txtarea.value.substring(endPos, txtarea.value.length);
		//set new selection
		if (isSample) {
			txtarea.selectionStart = startPos + tagOpen.length;
			txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
		} else {
			txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
			txtarea.selectionEnd = txtarea.selectionStart;
		}
		//restore textarea scroll position
		txtarea.scrollTop = textScroll;
	} 

	function checkSelectedText(){
		if (!selText) {
			selText = sampleText;
			isSample = true;
		} else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
			selText = selText.substring(0, selText.length - 1);
			tagClose += ' '
		} 
	}

}

// $(InsertButtonsIntoToolBarInForm);


// </source>