MediaWiki:Gadget-LegacyToolbar2006.js

Материал из Википедии — свободной энциклопедии
Перейти к навигации Перейти к поиску
Возможно, этот код документирован.

После сохранения или недавних изменений очистите кэш браузера.

/**
 * Interface for the classic edit toolbar.
 *
 * Adapted from MediaWiki Core, before it was removed from it on 2018-10-17
 */
( function () {
	var toolbar, isReady, $toolbar, queue, slice, $currentFocused;

	/**
	 * Internal helper that does the actual insertion of the button into the toolbar.
	 *
	 * For backwards-compatibility, passing `imageFile`, `speedTip`, `tagOpen`, `tagClose`,
	 * `sampleText` and `imageId` as separate arguments (in this order) is also supported.
	 *
	 * @private
	 *
	 * @param {Object} button Object with the following properties.
	 *  You are required to provide *either* the `onClick` parameter, or the three parameters
	 *  `tagOpen`, `tagClose` and `sampleText`, but not both (they're mutually exclusive).
	 * @param {string} [button.imageFile] Image to use for the button.
	 * @param {string} button.speedTip Tooltip displayed when user mouses over the button.
	 * @param {Function} [button.onClick] Function to be executed when the button is clicked.
	 * @param {string} [button.tagOpen]
	 * @param {string} [button.tagClose]
	 * @param {string} [button.sampleText] Alternative to `onClick`. `tagOpen`, `tagClose` and
	 *  `sampleText` together provide the markup that should be inserted into page text at
	 *  current cursor position.
	 * @param {string} [button.imageId] `id` attribute of the button HTML element. Can be
	 *  used to define the image with CSS if it's not provided as `imageFile`.
	 * @param {string} [speedTip]
	 * @param {string} [tagOpen]
	 * @param {string} [tagClose]
	 * @param {string} [sampleText]
	 * @param {string} [imageId]
	 */
	function insertButton( button, speedTip, tagOpen, tagClose, sampleText, imageId ) {
		var $button;

		// Backwards compatibility
		if ( typeof button !== 'object' ) {
			button = {
				imageFile: button,
				speedTip: speedTip,
				tagOpen: tagOpen,
				tagClose: tagClose,
				sampleText: sampleText,
				imageId: imageId
			};
		}

		if ( button.imageFile ) {
			$button = $( '<img>' ).attr( {
				src: button.imageFile,
				alt: button.speedTip,
				title: button.speedTip,
				id: button.imageId || undefined,
				'class': 'mw-toolbar-editbutton'
			} );
		} else {
			$button = $( '<div>' ).attr( {
				title: button.speedTip,
				id: button.imageId || undefined,
				'class': 'mw-toolbar-editbutton'
			} );
		}

		$button.click( function ( e ) {
			if ( button.onClick !== undefined ) {
				button.onClick( e );
			} else {
				toolbar.insertTags( button.tagOpen, button.tagClose, button.sampleText );
			}

			return false;
		} );

		$toolbar.append( $button );
	}

	isReady = false;
	$toolbar = false;

	/**
	 * @private
	 * @property {Array}
	 * Contains button objects (and for backwards compatibility, it can
	 * also contains an arguments array for insertButton).
	 */
	queue = [];
	slice = queue.slice;

	toolbar = {

		/**
		 * Add buttons to the toolbar.
		 *
		 * Takes care of race conditions and time-based dependencies by placing buttons in a queue if
		 * this method is called before the toolbar is created.
		 *
		 * For backwards-compatibility, passing `imageFile`, `speedTip`, `tagOpen`, `tagClose`,
		 * `sampleText` and `imageId` as separate arguments (in this order) is also supported.
		 *
		 * @inheritdoc #insertButton
		 */
		addButton: function () {
			if ( isReady ) {
				insertButton.apply( toolbar, arguments );
			} else {
				// Convert arguments list to array
				queue.push( slice.call( arguments ) );
			}
		},

		/**
		 * Add multiple buttons to the toolbar (see also #addButton).
		 *
		 * Example usage:
		 *
		 *     addButtons( [ { .. }, { .. }, { .. } ] );
		 *     addButtons( { .. }, { .. } );
		 *
		 * @param {...Object|Array} [buttons] An array of button objects or the first
		 *  button object in a list of variadic arguments.
		 */
		addButtons: function ( buttons ) {
			if ( !Array.isArray( buttons ) ) {
				buttons = slice.call( arguments );
			}
			if ( isReady ) {
				buttons.forEach( function ( button ) {
					insertButton( button );
				} );
			} else {
				// Push each button into the queue
				queue.push.apply( queue, buttons );
			}
		},

		/**
		 * Apply tagOpen/tagClose to selection in currently focused textarea.
		 *
		 * Uses `sampleText` if selection is empty.
		 *
		 * @param {string} tagOpen
		 * @param {string} tagClose
		 * @param {string} sampleText
		 */
		insertTags: function ( tagOpen, tagClose, sampleText ) {
			if ( $currentFocused && $currentFocused.length ) {
				$currentFocused.textSelection(
					'encapsulateSelection', {
						pre: tagOpen,
						peri: sampleText,
						post: tagClose
					}
				);
			}
		}
	};

	// For backwards compatibility. Used to be called from EditPage.php, maybe other places as well.
	toolbar.init = $.noop;

	// Expose API publicly
	mw.toolbar = toolbar;

	$( function () {
		var $textBox, i, button;

		// Used to determine where to insert tags
		$currentFocused = $( '#wpTextbox1' );

		if ( mw.loader.getState( 'ext.wikiEditor' ) === 'ready' ) {
			// do nothing if wikiEditor 2010 is ready
		} else {

			// Populate the selector cache for $toolbar
			$toolbar = $( '#toolbar' );

			if ( $toolbar.length === 0 ) {
				$textBox = $( '#wpTextbox1' );
				if ( $textBox.length === 0 ) {
					return;
				}
				$toolbar = $( '<div>' ).attr( { id: 'toolbar' } );
				$toolbar.css( 'clear', 'none' );
				$toolbar.insertBefore( $textBox );
			}

			for ( i = 0; i < queue.length; i++ ) {
				button = queue[ i ];
				if ( Array.isArray( button ) ) {
					// Forwarded arguments array from mw.toolbar.addButton
					insertButton.apply( toolbar, button );
				} else {
					// Raw object from mw.toolbar.addButtons
					insertButton( button );
				}
			}
		}
		// Clear queue
		queue.length = 0;

		// This causes further calls to addButton to go to insertion directly
		// instead of to the queue.
		// It is important that this is after the one and only loop through
		// the queue
		isReady = true;

		// Apply to dynamically created textboxes as well as normal ones
		$( document ).on( 'focus', 'textarea, input:text', function () {
			$currentFocused = $( this );
		} );
	} );

}() );

( function () {

function addOldToolbarButtons() {
	mw.toolbar.addButtons( {
		imageFile: '//upload.wikimedia.org/wikipedia/commons/e/e2/Button_bold.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-bold' ),
		tagOpen: '\'\'\'',
		tagClose: '\'\'\'',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-bold-example' ),
		imageId: 'mw-editbutton-bold'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/1/1d/Button_italic.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-italic' ),
		tagOpen: '\'\'',
		tagClose: '\'\'',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-italic-example' ),
		imageId: 'mw-editbutton-italic'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/c/c0/Button_link.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-link' ),
		tagOpen: '[[',
		tagClose: ']]',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-ilink-example' ),
		imageId: "mw-editbutton-link"
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/e/ec/Button_extlink.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-xlink' ),
		tagOpen: '[',
		tagClose: ']',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-xlink-example' ),
		imageId: 'mw-editbutton-extlink'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/7/78/Button_head_A2.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-heading' ),
		tagOpen: '== ',
		tagClose: ' ==',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-heading-example' ),
		imageId: 'mw-editbutton-headline'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/d/de/Button_image.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-file' ),
		tagOpen: '[[Файл:',
		tagClose: '|thumb|Описание]]',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-file-example' ),
		imageId: 'mw-editbutton-image'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/8/82/Nowiki_icon.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-nowiki' ),
		tagOpen: '<nowiki\>',
		tagClose: '</' + 'nowiki>',
		sampleText: mw.msg( 'wikieditor-toolbar-tool-nowiki-example' ),
		imageId: 'mw-editbutton-nowiki'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/6/6d/Button_sig.png',
		speedTip: mw.msg( 'wikieditor-toolbar-tool-signature' ),
		tagOpen: '-- ~~\~~',
		tagClose: '',
		sampleText: '',
		imageId: 'mw-editbutton-signature'
	},
	{
		imageFile: '//upload.wikimedia.org/wikipedia/commons/0/0d/Button_hr.png',
		speedTip: mw.msg( 'hr_tip' ),
		tagOpen: '--\--',
		tagClose: '',
		sampleText: '',
		imageId: 'mw-editbutton-hr'
	},
	{
		speedTip: 'Перенаправление',
		imageFile: '//upload.wikimedia.org/wikipedia/ru/1/1d/Button_redirect_rus.png',
		tagOpen: '#перенаправление [[',
		sampleText: 'Название целевой страницы',
		tagClose: ']]',
		imageId: 'mw-editbutton-redirect'
	},
	{
		speedTip: 'Категория',
		imageFile: '//upload.wikimedia.org/wikipedia/commons/3/3c/Button_cat_ru.png',
		tagOpen: '[\[Категория:',
		sampleText: '',
		tagClose: ']]\n',
		imageId: 'mw-editbutton-category'
	},
	{
		speedTip: 'Комментарий',
		imageFile: '//upload.wikimedia.org/wikipedia/en/3/34/Button_hide_comment.png',
		tagOpen: '<!-- ',
		sampleText: 'Комментарий',
		tagClose: ' -->',
		imageId: 'mw-editbutton-comment'
	},
	{
		speedTip: 'Развёрнутая цитата',
		imageFile: '//upload.wikimedia.org/wikipedia/en/f/fd/Button_blockquote.png',
		tagOpen: '<blockquote>\n',
		sampleText: 'Развёрнутая цитата одним абзацем',
		tagClose: '\n</blockquote>',
		imageId: 'mw-editbutton-blockquote'
	},
	{
		speedTip: 'Вставить таблицу',
		imageFile: '//upload.wikimedia.org/wikipedia/en/6/60/Button_insert_table.png',
		tagOpen: '{| class="wikitable"\n|',
		sampleText: '-\n! заголовок 1\n! заголовок 2\n! заголовок 3\n|-\n| строка 1, ячейка 1\n| строка 1, ячейка 2\n| строка 1, ячейка 3\n|-\n| строка 2, ячейка 1\n| строка 2, ячейка 2\n| строка 2, ячейка 3',
		tagClose: '\n|}',
		imageId: 'mw-editbutton-insert_table'
	},
	{
		speedTip: 'Сноска',
		imageFile: '//upload.wikimedia.org/wikipedia/commons/7/79/Button_reflink.png',
		tagOpen: '<ref\>',
		sampleText: 'Вставьте сюда текст сноски',
		tagClose: '</ref>',
		imageId: 'mw-editbutton-reflink'
	} );

	// Кнопки популярных гаджетов
	var $gadgetToolbar = $( '<div>' )
		.attr( 'id', 'gadget-toolbar' )
		.prependTo( '#toolbar' );

	mw.loader.using( 'mediawiki.util' ).done( function () {
		mw.util.addCSS( '\
			#gadget-toolbar {\
				float: left;\
			}\
		' );
	} );

	function addOldToolbarButton( button ) {
		$( '<div>' )
			.addClass( 'mw-toolbar-editbutton' )
			.attr( 'alt', button.alt )
			.attr( 'title', button.title )
			.css( button.css )
			.appendTo( $gadgetToolbar )
			.click( function () {
				if ( window[ button.callbackFuncName ] ) {
					window[ button.callbackFuncName ]();
				}
			} );
	}

	var gadgets = {
		wikificator: {
			alt: 'Викификатор',
			title: 'Викификатор — автоматический обработчик текста',
			css: {
				width: '69px',
				backgroundImage: 'url(//upload.wikimedia.org/wikipedia/commons/3/38/Button_wikify.png)',
			},
			callbackFuncName: 'Wikify',
		},
		urldecoder: {
			alt: 'Раскодировщик URL',
			title: 'Раскодировать URL перед курсором или все URL в выделенном тексте',
			css: { backgroundImage: 'url(//upload.wikimedia.org/wikipedia/commons/6/63/Link_go_toolbar.png)' },
			callbackFuncName: 'urlDecoderRun',
		},
		Wikilinker: {
			alt: 'Викиссыльщик',
			title: 'Викиссыльщик — подбирает вики-ссылку для выделенного слова или словосочетания',
			css: { backgroundImage: 'url(//upload.wikimedia.org/wikipedia/commons/a/ad/Wikilinker_toolbar.png)' },
			callbackFuncName: 'WikiLinker',
		},
		refToolbar: {
			alt: 'Добавить шаблон цитирования',
			title: 'Добавить шаблон цитирования',
			css: { backgroundImage: 'url(//upload.wikimedia.org/wikipedia/commons/e/ea/Button_easy_cite.png)' },
			callbackFuncName: 'refbuttons',
		},
	};

	for ( var name in gadgets ) {
		if ( mw.user.options.get( 'gadget-' + name ) || name === 'wikificator' ) {
			mw.loader.using( [ 'ext.gadget.' + name ] ).done( function ( name ) {
				addOldToolbarButton( gadgets[ name ] );
			}.bind( this, name ) );
		}
	}

	mw.hook( 'legacy.toolbar.ready' ).fire();
}

if ( [ 'edit', 'submit' ].indexOf( mw.config.get( 'wgAction' ) ) !== -1 ) {
	mw.loader.using( [ 'user.options' ], function () {
		if ( mw.user.options.get( 'usebetatoolbar' ) != 1 ) {
			$.when( mw.loader.using( [ 'mediawiki.api' ] ) )
				.then( function() {
					return new mw.Api().loadMessagesIfMissing( [
						'wikieditor-toolbar-tool-bold-example', 'wikieditor-toolbar-tool-bold',
						'wikieditor-toolbar-tool-italic-example', 'wikieditor-toolbar-tool-italic',
						'wikieditor-toolbar-tool-ilink-example', 'wikieditor-toolbar-tool-link',
						'wikieditor-toolbar-tool-xlink-example', 'wikieditor-toolbar-tool-xlink',
						'wikieditor-toolbar-tool-heading-example', 'wikieditor-toolbar-tool-heading',
						'wikieditor-toolbar-tool-file-example', 'wikieditor-toolbar-tool-file',
						'wikieditor-toolbar-tool-nowiki-example', 'wikieditor-toolbar-tool-nowiki',
						'wikieditor-toolbar-tool-signature', 'hr_tip'
					], { amlang: mw.config.get( 'wgUserLanguage' ) } );
				} )
				.then( function () {
					$( addOldToolbarButtons );
				} );
		}
	} );
}

}() );