User:Pathoschild/Scripts/TemplateScript

From Meta, a Wikimedia project coordination wiki
Jump to: navigation, search

TemplateScript

Part of wikimedia-contrib
report a bug or suggestion

TemplateScript adds a menu of configurable templates and scripts to the sidebar. It automatically handles templates for various forms (from editing to protection), edit summaries, auto-submission, and filtering which templates are shown based on namespace, form, or arbitrary conditions. Templates can be inserted at the cursor position or at a preconfigured position. For more technical users, a script can be invoked when a sidebar link is activated — and even combined with templating.

It should be compatible with all Wikimedia skins and common browsers.

Installation[edit]

  1. Copy the following code to User:your user name/common.js. (Don't remove the @update-token, unless you don't want your script to be updated for future changes.)
    /**
     * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
     * @see https://meta.wikimedia.org/wiki/User:Pathoschild/Scripts/TemplateScript
     * @update-token [[file:pathoschild/templatescript.js]]
     */
    // <pre>
    $.getScript('https://raw.github.com/pathoschild/wikimedia-contrib/master/pathoschild.templatescript.js', function() {
    	pathoschild.TemplateScript.Add([
    		{ name: 'welcome', template: '{{subst:welcome}} ~~~~', position: 'after', editSummary: 'welcome!', forNamespaces: 3, forActions: 'edit' },
    		// add your own templates or scripts here
    	]);
    });
    // </pre>
    
  2. Refresh your browser to reload the JavaScript. (In Chrome or Firefox, press [CTRL] and [R] at the same time.)

Usage[edit]

Creating templates[edit]

You define templates and scripts by passing a Template-like object to the pathoschild.TemplateScript.Add() function. Here's an example of several Template options. This will create a new sidebar box with the header "Being nice", with a link with the text "Welcome" — but only if you're editing a user's talk page (forNamespaces). When you click the link, it will insert "{{subst:welcome}} ~~~~" at the bottom of the edit box, and set the edit summary to "Welcome!".

pathoschild.TemplateScript.Add({
	category: 'Being nice',
	name: 'Welcome',
	template: '{{subst:welcome}} ~~~~',
	position: 'bottom',
	editSummary: 'Welcome!',
	forNamespaces: 3
});

You can also pass an array of templates to the function:

pathoschild.TemplateScript.Add([
	{
		category: 'Being nice',
		name: 'Welcome',
		template: '{{subst:welcome}} ~~~~',
		position: 'bottom',
		editSummary: 'Welcome!',
		forNamespaces: 3
	},
	{
		category: 'Being nice',
		name: 'Hi',
		template: '{{subst:hi}} ~~~~',
		position: 'bottom',
		editSummary: 'Hi!',
		forNamespaces: 3
	}
]);

If you need to repeat some values, you can use the alternative pathoschild.TemplateScript.AddWith() function that lets you specify common fields. For example, this code is equivalent to the last example:

pathoschild.TemplateScript.AddWith(
	{category:'Being nice', position:'bottom', forNamespaces:3},
	[
		{ name:'Welcome', template:'{{subst:welcome}} ~~~~', editSummary:'Welcome!' },
		{ name: 'Hi', template:'{{subst:hi}} ~~~~', editSummary:'Hi!' }
	]
);

See Template for a full list of options you can pass. (More technical users can read the detailed code documentation in the source code.)

Template objects[edit]

Template
The pathoschild.TemplateScript.Template object contains all the options for a template or script. You must specify a name and template (or script), but all other fields are optional.
User interface and enabling:
option type default value purpose
name string (required) The name displayed as the sidebar link text.
enabled boolean true Whether this template is available.
category string 'TemplateScript' An arbitrary category name (for grouping templates into multiple sidebars), or null to use the default sidebar.
forActions string or string[] (all actions) The wgAction values for which the template is enabled.
forNamespaces int or int[] (all namespaces) The namespaces in which the template is enabled.
Behaviour:
option type default value purpose
template string null The text to insert into the main input box.
position string 'cursor'
or 'replace'
The position at which to insert the template. The default value is 'cursor' when editing a page, and 'replace' in all other cases.
isMinorEdit boolean false Whether to mark the edit as minor (if applicable).
editSummary string null The edit summary to use (if applicable).
editSummaryPosition string 'replace' The position at which to insert the edit summary.
headline string null The subject or headline to use (if applicable). This appears when editing a page with &section=new in the URL.
headlinePosition string 'replace' The position at which to insert the headline.
Scripting:
option type default value purpose
autoSubmit boolean false Whether to submit the form automatically after insertion.
script function null An arbitrary JavaScript function that is called after the template and edit summary are applied, but before autoSubmit. It is passed a reference to the Context object.
Position
The pathoschild.TemplateScript.Position values represent the insertion behaviour. These can be specified either as a constant (pathoschild.TemplateScript.Position.cursor) or by name ('cursor').
value meaning
before Insert before the text.
after Insert after the text.
cursor Insert the template at the current cursor position (replacing the selected text, if any).
replace Replace the current text entirely.
Context
The pathoschild.TemplateScript.Context object provides convenient access to properties about the current page. This is passed to Template scripts. (This object is populated by TemplateScript; changing the values yourself may cause unexpected behaviour.)
value type meaning
namespace int The number of the current namespace.
action string The current MediaWiki action.
singleton pathoschild.TemplateScript The TemplateScript instance for the page.
$target jQuery The primary input element (e.g., the edit textarea) for the current form.
$editSummary jQuery The edit summary input element (if relevant to the current form).

Examples[edit]

  • A simple template and a simple script:
    pathoschild.TemplateScript.Add([
    	{
    		name: 'header',
    		template: '{{header | some parameter = true }}',
    		position: 'before',
    		editSummary: 'added {{header}}',
    		forNamespaces: 0,
    		forActions: 'edit'
    	},
    	{
    		name: 'alert test',
    		script: function ($target) {
    			alert('The edit box says: "' + $target.val() + '".');
    		},
    		forActions: 'edit'
    	}
    ]);
    
  • A combination template and script:
    pathoschild.TemplateScript.Add({
    	name: 'current URL',
    	template: '<$URL>',
    	script: function (context) {
    		context.$target.val(context.$target.val().replace(/<\$URL>/g, location.href));
    	}
    });
    
  • A more comprehensive example, showing a full list of deletion templates for the English Wikisource, complete with logic to only show the relevant templates:
    /* editing pages */
    pathoschild.TemplateScript.AddWith(
    	{ forActions: 'edit' },
    	[
    		/* main namespace */
    		{
    			name: 'header',
    			template: '{{header\n | title    =\n | author   =\n | section  =\n | previous =\n | next     =\n | notes    =\n}}',
    			position: 'before',
    			forNamespaces: 0
    		},
     
    		/* talk namespace */
    		{
    			name: 'featured talk',
    			template: '{{featured talk\n | month   = {{subst:CURRENTMONTH}}\n | year    = {{subst:CURRENTYEAR}}\n | archive = {{subst:CURRENTYEAR}}/{{subst:CURRENTMONTH}}\n}}',
    			forNamespaces: 1
    		},
    		{
    			name: 'textinfo',
    			template: '{{textinfo\n| edition      =\n| source       =\n| contributors =\n| progress     =\n| notes        =\n| proofreaders =\n}}',
    			position: 'before',
    			editSummary: '{{textinfo}}',
    			forNamespaces: 1
    		},
     
    		/* author namespace */
    		{
    			name: 'author',
    			template: '{{author\n |name           =\n |last_initial   =\n |dates          =\n |description    =\n |image          =\n |wikipedia_link =\n |wikiquote_link =\n |commons_link   =\n}}',
    			forNamespaces: 102
    		}
    	]
    );
     
    /* deleting pages */
    pathoschild.TemplateScript.AddWith(
    	{ forActions: 'delete', category: 'Consensus' },
    	[
    		{
    			name: 'Copyvio discussion',
    			template: '[[WS:COPYVIO|Possible copyright violation]]',
    			category: 'Consensus'
    		},
    		{
    			name: 'Proposed',
    			template: '[[WS:DEL|Proposed deletion]]',
    			category: 'Consensus'
    		}
    	]
    );
    pathoschild.TemplateScript.AddWith(
    	{ forActions: 'delete', category: 'Speedy' },
    	[
    		{
    			name: 'G1 no meaningful',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G1 ("No meaningful content or history.")'
    		}, {
    			name: 'G2 recreation',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G2 ("Reposted content previously deleted...")'
    		}, {
    			name: 'G3 banned user',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G3 ("content created and edited solely by a banned user after they were banned...")'
    		}, {
    			name: 'G4 redundant',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G4 ("Two versions of the same text on different pages...")'
    		}, {
    			name: 'G5 beyond scope',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G5 ("...clearly lies outside the [[WS:WWI|scope of Wikisource]]...")'
    		}, {
    			name: 'G6 copyvio',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G6 ("...clear and proven copyright violation...")'
    		}, {
    			name: 'G6 re-copyvio',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G6 ("...content previously deleted as a copyright violation...")'
    		}, {
    			name: 'G6 copyvio author',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G6 ("...author pages for authors whose works are all copyrighted...")'
    		}, {
    			name: 'G7 author\'s request',
    			template: '[[WS:CSD|Criteria for speedy deletion]] G7 ("Deletion per request of the author...")'
    		}, {
    			name: 'A1 transwikied',
    			template: '[[WS:CSD|Criteria for speedy deletion]] A1 ("Articles [[m:transwiki|transwikied]] to another project...")'
    		}, {
    			name: 'A1 transwikied (commons)',
    			template: '[[WS:CSD|Criteria for speedy deletion]] A1 ("...images uploaded to the [[commons:|Wikimedia commons]] with the original contributor noted...")'
    		}, {
    			name: 'A2 non-notable',
    			template: '[[WS:CSD|Criteria for speedy deletion]] A2 ("...not significantly peer-reviewed or previously published in a significant edition or forum.")'
    		}, {
    			name: 'A3 no authorship info',
    			template: '[[WS:CSD|Criteria for speedy deletion]] A3 ("Works without authorship information...")'
    		}, {
    			name: 'M1 trivial',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M1 ("...deletion as part of a page move or history merge, as long as the action requiring the deletion is uncontroversial.")'
    		}, {
    			name: 'M2 redirect (new)',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M2 ("Unneeded redirects from page titles created within the last week...")'
    		}, {
    			name: 'M2 redirect (old)',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M2 ("...[unneeded] redirects tagged with {{subst:dated soft redirect|"[[new title]]"}} for at least two months.")'
    		}, {
    			name: 'M2 redirect (broken)',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M2 ("...Redirects to inexistant pages...)"'
    		}, {
    			name: 'M3 redirect (article to other ns)',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M3 ("Internamespace redirects from the article namespace to any other namespace.")'
    		}, {
    			name: 'M4 talk page',
    			template: '[[WS:CSD|Criteria for speedy deletion]] M4 ("Unneeded talk: a discussion page for deleted or inexistant content.")'
    		}
    	]
    );
     
    /* various forms */
    pathoschild.TemplateScript.Add([
    	{
    		forActions: 'protect',
    		name: 'featured',
    		template: '[[WS:FT|Featured text]] (see the [[WS:PP|protection policy]])',
    		position: 'replace'
    	},
    	{
    		forActions: 'move',
    		name: 'standardized',
    		template: '[[WS:STYLE|Standardised]]',
    		position: 'replace'
    	}
    ]);
    

Troubleshooting[edit]

  1. Don't use $element.text() or $element.html() to edit input boxes.
    Always use $element.val() to change input box content. The $element.text() or $element.html() methods modify the element HTML directly, not the current value — these will cause the user's changes to be lost.

Regex editor[edit]

TemplateScript includes a default tool called the regex editor (see live example), which lets you define any number of custom regular expressions and apply them to the text. You can disable this feature by adding the following code before TemplateScript:

var pathoschild = pathoschild || {};
pathoschild.disableRegexEditor = true;


As a gadget or framework[edit]

There is only one TemplateScript instance on the page: as long as it has been defined at least once, you can call methods like Add() at any time (even if the page is not fully loaded), in any order, and multiple times. This makes it easy to use it in gadgets, since it will never conflict with other usages. The script support makes TemplateScript useful as a framework for other tools (such as the regex editor), letting them easily add their own sidebars with arbitrary scripts:

An example sidebar created for another tool.
pathoschild.TemplateScript.Add({
	category: 'My cool sidebar',
	name: 'Replace every answer',
	script: function ($target) {
		$target.val($target.val().replace(/answer/g, '42'));
		MyGadget.DoStuff();
	}
});

A sidebar is not necessarily associated with a form: if no options are specified, it will always be visible.

See also[edit]