Extension:WikiEditor/Toolbar customization

From mediawiki.org

This article explains the technical details of customizing the toolbar. It requires a basic level of understanding of JavaScript.

If you just need some quick working code that you can copy into your user JS, see the customizations library.

Basic setup[edit]

Scripts and gadgets[edit]

Before a script or gadget is able to manipulate the toolbar provided by WikiEditor, the following things must happen:

  1. Set the following in LocalSettings.php :
  2. The module "ext.wikiEditor" needs to be loaded which is usually done by invoking the WikiEditor extension.
  3. Add the following code to your User:YourUserName/common.js (or your MediaWiki:Common.js for a site-wide change) to customize the toolbar:
// Check if we're editing a page.
if ( [ 'edit', 'submit' ].indexOf( mw.config.get( 'wgAction' ) ) !== -1 ) {
	// Add a hook handler.
	mw.hook( 'wikiEditor.toolbarReady' ).add( function ( $textarea ) {
		// Configure a new toolbar entry on the given $textarea jQuery object.
		$textarea.wikiEditor( 'addToToolbar', {
			/* Your code goes here */
		} );
	} );
}

… and replace the line /* Your code goes here */ by the code which defines each button added. Multiple snippets can be added by adding multiple separate $textarea.wikiEditor( 'addToToolbar' … ) calls.

Extensions[edit]

Extensions wishing to customize the toolbar should first set up a module (with a dependency on ext.wikiEditor) and then add the following (e.g. in extensions/MyExt/modules/mymodule/init.js):

( function () {
	mw.hook( 'wikiEditor.toolbarReady' ).add( function ( $textarea ) {
		$textarea.wikiEditor( 'addToToolbar', {
			/* Toolbar configuration goes here. */
		} );
	} );
}() );

Configuration structure[edit]

The toolbar widget is defined by a jQuery plugin from module jquery.wikiEditor. You can look at the configuration for the default toolbar on module jquery.wikiEditor.toolbar.config to see how you can modify the toolbar.

You can modify the toolbar even after it's been built (see example above) by calling the .wikiEditor() function on the textarea. You will need to do this inside an $(document).ready(function() {}); call, as already mentioned.

action[edit]

  • type: one of "encapsulate", "replace", "callback", "dialog"
  • options: for "encapsulate" or "replace" types, carries options for jquery.textSelection module (pre, peri, post); regex, regexReplace
  • execute: for "callback" type, a callable function which will be passed the WikiEditor context
  • module: for "dialog" type, named reference to a WikiEditor add-in dialog module to open

Example:

action: {
	type: 'encapsulate',
	options: {
		pre: "'''",
		peri: mw.msg( 'wikieditor-toolbar-tool-bold-example' ),
		post: "'''"
	}
}

Another example, using a callback function for the most flexibility in what should happen when the button is pressed:

action: {
	type: 'callback',
	execute: function ( context ) {
		// The context object contains things such as the toolbar and the textarea.
		console.log( context );
		context.$textarea.css( 'background-color', 'pink' );
	}
}

If you want to use type: 'dialog', you must register a function that returns the dialog in advance using wikiEditor( 'addModule', DialogFunc()).

button[edit]

  • type: "button"
  • icon or oouiIcon string required: short key name or URL to icon
  • label string: label string (use mw.msg( key ) for localization)
  • #action

toggle[edit]

Toggles are like buttons but with a binary state. The button can be pressed (active) or non-pressed. (Since 1.32)

  • type: "toggle"
  • icon or oouiIcon string required: short key name or URL to icon
  • label string: label string (use mw.msg( key ) for localization)
  • #action

You need to track the state yourself, the toggle button will not do it for you. After a callback, update the state, find the buttonelement and call $button.data( 'setActive' )(boolean); to make the button reflect the new state.

select[edit]

A dropdown menu with menuitems, each menuitem having its own action

  • type: "select"
  • icon or oouiIcon string required: short key name or URL to icon
  • label string: label string (use mw.msg( key ) for localization)
  • list object with dropdown menu items, each with their own label and #action

element[edit]

Insert a raw DOM element. When you use this, you are responsible for everything (labels, event handling, accessiblity, etc.) but have the freedom to do whatever you want (dropdowns, buttons with visible labels, etc.).

  • type: "element"
  • element: either a htmlString, HTMLElement, Text, Array, jQuery object, a function returning any of the aforementioned, or a OO.ui.HTMLSnippet to be inserted.

For example, a button added to the secondary end of the toolbar that displays an alert when clicked:

	$textarea.wikiEditor( 'addToToolbar', {
		section: 'secondary',
		group: 'default',
		tools: {
			dothing: {
				type: 'element',
				element: function ( context ) {
					// Note that the `context` object contains various useful references.
					console.log( context );
					var button = new OO.ui.ButtonInputWidget( {
						label: 'Do a thing',
						icon: 'hieroglyph'
					} );
					button.connect( null, {
						click: function ( e ) {
							// Do whatever is required when the button is clicked.
							console.log( e );
							OO.ui.alert( 'A thing is done.' );
						}
					} );
					return button.$element;
				}
			}
		}
	} );

booklet[edit]

  • type: "booklet"
  • label string: label string (use mw.msg( key ) for localization)
  • deferLoad boolean
  • pages object: map of name keys to further objects:
    • layout string required: 'table' or 'characters'
    • label string: label string (use mw.msg( key ) for localization)
    • headings string[]: array of objects? {text: mw.message( key ).parse() } ⁇
    • rows object[] optional?: array of objects? {'row key name': {message object?}}
    • characters object[] optional?: array of strings of little character bits for insertion, or objects specifying actions:
      • A string is interpreted as a character or string to insert at the cursor position.
      • An array with 2 strings will use the first string as the label, and the second string as the string to be inserted.
      • An object containing action and label properties will perform the action (used to split text to insert before and after the selection).

Default sections[edit]

The default WikiEditor toolbar has the following sections:

  • The main section which is always visible, with the groups format and insert.
  • The secondary is at the opposite end from the main section, and contains the default group that is empty by default.
  • The advanced section, with the groups heading, format, size, insert and search.
  • The characters section, with pages latin, latinextended, ipa, symbols, greek, cyrillic, arabic, hebrew, bangla, telugu, sinhala and gujarati
  • The help section, with pages format, link, heading, list, file, reference and discussion.

Adding things[edit]

The general format for adding things is as follows:

mw.hook( 'wikiEditor.toolbarReady' ).add( function ( $textarea ) {
	$textarea.wikiEditor( 'addToToolbar', {
		// Configuration object here
	} );
} );

Some specific examples are displayed in the sections below.

Add a toolbar section[edit]

$textarea.wikiEditor( 'addToToolbar', {
	sections: {
		emoticons: {
			type: 'toolbar', // Can also be 'booklet',
			label: 'Emoticons'
			// or label: mw.msg( 'section-emoticons-label' ) for a localized label
		}
	}
} );

Add a group to an existing toolbar section[edit]

$textarea.wikiEditor( 'addToToolbar', {
	section: 'emoticons',
	groups: {
		faces: {
			label: 'Faces' // or use mw.msg() for a localized label, see above
		}
	}
} );

Add a button to an existing toolbar group[edit]

$textarea.wikiEditor( 'addToToolbar', {
	section: 'emoticons',
	group: 'faces',
	tools: {
		smile: {
			label: 'Smile!', // or use mw.message( key ).escaped() for a localized label, see above
			type: 'button',
			icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Gnome-face-smile.svg/22px-Gnome-face-smile.svg.png',
			action: {
				type: 'encapsulate',
				options: {
					pre: ":)" // text to be inserted
				}
			}
		}
	}
} );

Filter which namespaces should or should not generate added buttons[edit]

Ex. - To have a button generated only when editing any Talk: namespace page, add the highlighted line below.
$textarea.wikiEditor( 'addToToolbar', {
	section: 'emoticons',
	group: 'faces',
	tools: {
		smile: {
			label: 'Smile!', // or use mw.msg() for a localized label, see above
			filters: [ 'body.ns-talk' ],
			type: 'button',
			icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Gnome-face-smile.svg/22px-Gnome-face-smile.svg.png',
			action: {
				type: 'encapsulate',
				options: {
					pre: ":)" // text to be inserted
				}
			}
		}
	}
} );
Ex. - To have a button generated in all namespaces except the User: and Template: namespaces, add the highlighted line below.
$textarea.wikiEditor( 'addToToolbar', {
	section: 'emoticons',
	group: 'faces',
	tools: {
		smile: {
			label: 'Smile!', // or use mw.msg() for a localized label, see above
			filters: [ 'body:not(.ns-2, .ns-10)' ],
			type: 'button',
			icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Gnome-face-smile.svg/22px-Gnome-face-smile.svg.png',
			action: {
				type: 'encapsulate',
				options: {
					pre: ":)" // text to be inserted
				}
			}
		}
	}
} );

Add a drop-down picklist[edit]

$textarea.wikiEditor( 'addToToolbar', {
	section: 'main',
	groups: {
		list: {
			tools: {
				templates: {
					label: 'Templates',
					type: 'select',
					list: {
						'Ping-button': {
							label: '{{Ping}}',
							action: {
								type: 'encapsulate',
								options: {
									pre: '{{Ping|',
									post: '}}'
								}
							}
						},
						'Clear-button': {
							label: 'Clear',
							action: {
								type: 'encapsulate',
								options: {
									pre: '{{Clear}}'
								}
							}
						},
						'Done-button': {
							label: 'Done',
							action: {
								type: 'encapsulate',
								options: {
									pre: '{{Done}}'
								}
							}
						}
					}
				}
			}
		}
	}
} );

Add a booklet section[edit]

$textarea.wikiEditor( 'addToToolbar', {
	sections: {
		info: {
			type: 'booklet',
			label: 'Info'
		}
	}
} );

Add a page to an existing booklet section[edit]

$textarea.wikiEditor( 'addToToolbar', {
	section: 'info',
	pages: {
		colors: {
			layout: 'table',
			label: 'Colors',
			headings: [
				{ text: 'Name' }, // or use mw.message( key ).parse() for localization, see also above
				{ text: 'Temperature' },
				{ text: 'Swatch' }
			],
			rows: [
				{
					name: { text: 'Red' },
					temp: { text: 'Warm' },
					swatch: { html: '<div style="width:10px;height:10px;background-color:red;">' }
				},
				{
					name: { text: 'Blue' },
					temp: { text: 'Cold' },
					swatch: { html: '<div style="width:10px;height:10px;background-color:blue;">' }
				},
				{
					name: { text: 'Silver' },
					temp: { text: 'Neutral' },
					swatch: { html: '<div style="width:10px;height:10px;background-color:silver;">' }
				}
			]
		}
	}
} );

Add a special characters page[edit]

$textarea.wikiEditor( 'addToToolbar', {
	section: 'characters',
	pages: {
		emoticons: {
			layout: 'characters',
			label: 'Emoticons',
			characters: [ ':)', ':))', ':(', '<3', ';)' ]
		}
	}
} );

Note that this only works after the 'characters' section has been built.

Add a whole new group with snippets, that insert text before and after the cursor position or selected text[edit]

Instead of a string, we can use an object in the array of characters, with a label and action, to provide the text to insert before and after the cursor or selected text.

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
  'sections': {
    'snippets': {
      'type': 'booklet',
      'label': 'Useful Snippets',
      'pages': {
        'section-xml': {
          'label': 'XML Tags',
          'layout': 'characters',
          'characters': [
            '<references/>',
            {
              'action': {
                'type': 'encapsulate',
                'options': {
                  'pre': '<ref>',
                  'peri': '',
                  'post': '</ref>'
                }
              },
              'label': '<ref></ref>'
            }
          ]
        },
        'section-links': {
          'label': 'Wikilinks',
          'layout': 'characters',
          'characters': [
            {
              'action': {
                'type': 'encapsulate',
                'options': {
                  'pre': '[[Category:',
                  'peri': '',
                  'post': ']]'
                }
              },
              'label': '[[Category:]]'
            },
            {
              'action': {
                'type': 'encapsulate',
                'options': {
                  'pre': '[[File:',
                  'peri': '',
                  'post': ']]'
                }
              },
              'label': '[[File:]]'
            }
          ]
        }
      }
    }
  }
} );

Add characters to an existing special characters page[edit]

Additional characters can be injected during the building of the 'characters' section:

$(function() {
    $( '#wpTextbox1' ).on( 'wikiEditor-toolbar-buildSection-characters', function (event, section) {
        section.pages.symbols.characters.push('\u02be', '\u02bf');
    });
});

There is also an API function, but it only works after the 'characters' section has been built:

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
	'section': 'characters',
	'page': 'symbols',
	'characters': [ '\u02be', '\u02bf' ]
});

Removing things[edit]

Use the removeFromToolbar call to remove buttons from the toolbar. The following example removes the button for deprecated HTML element <big>:

/* Remove button for <big> */
$( '#wpTextbox1' ).wikiEditor( 'removeFromToolbar', {
	'section': 'advanced',
	'group': 'size',
	'tool': 'big'
});

Modifying things[edit]

We don't really have a nice API to modify things, unfortunately. The best we have is a hook to change the configuration of a section just before it's being built:

$( '#wpTextbox1' ).on( 'wikiEditor-toolbar-buildSection-sectionname', function( event, section ) {
	// Do stuff with section
} );

Example: adding localized icons[edit]

$( '#wpTextbox1' ).on( 'wikiEditor-toolbar-buildSection-main', function( event, section ) {
	// Add icons for bold (F) and italic (L) for Swedish (sv)
	// Don't overwrite them if they're already defined, so this hack can safely be removed once the
	// usability team incorporates these icons in the software
	if ( !( 'sv' in section.groups.format.tools.bold.icon ) ) {
		// There's already a bold F icon for German, use that one
		section.groups.format.tools.bold.icon['sv'] = 'format-bold-F.png';
		section.groups.format.tools.bold.offset['sv'] = [2, -214];
	}
	if ( !( 'sv' in section.groups.format.tools.italic.icon ) ) {
		// Use an icon from Commons for L
		section.groups.format.tools.italic.icon['sv'] = '//upload.wikimedia.org/wikipedia/commons/3/32/Toolbaricon_italic_L.png';
		section.groups.format.tools.italic.offset['sv'] = [2, -214];
	}
} );

Example: modifying button action[edit]

The solution below replaces the insertion of obsolete <big> tag with Big template, but could be used for any customisation of button actions in WikiEditor.

// Stop WikiEditor from inserting obsolete HTML tag / <nowiki>
$( '#wpTextbox1' ).on( 'wikiEditor-toolbar-buildSection-advanced', function( event, section ) {
	// The exact paths are available in jquery.wikiEditor.toolbar.config.js file of the extension
	section.groups.size.tools.big.action.options.pre = '{{big|';
	section.groups.size.tools.big.action.options.post = '}}';
} );
// </nowiki>

Determining when toolbar load is done[edit]

To be notified when the initial toolbar load is done, put:

$( '#wpTextbox1' ).on( 'wikiEditor-toolbar-doneInitialSections', function () {
    // Do something
} );

This is in WikiEditor wmf/1.21wmf8 and later. For example, GuidedTour repositions absolutely positioned guiders (a type of tooltip) at this point.

This should be used carefully, because your script can be loaded later than the moment the event fires.

So it is better to use a hook (it will work also when you run this after the page is fully loaded).

mw.hook( 'wikiEditor.toolbarReady' ).add( function ( $textarea ) {
    // Do something
} );

See also[edit]