Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * WikiEditor tools for Module editing
 *
 * The WikiEditor-Tools-loader gadget will only load this when editing a
 * page with Lua content model. Users not editing such pages will never have
 * it loaded.
 *
 * Suggest new help items on the talk page.
 */

( function () {

	'strict';

	var addModuleTemplates = function ( wikiEditor ) {

		var title = mw.config.get( 'wgTitle' );
		var moduleName = title.replace( /Module:/, '' ).replace( /\/.*/, '' );
		var canNs = mw.config.get( 'wgCanonicalNamespace' );
		var isTestcases = ( /\/testcases$/.test( mw.config.get( 'wgTitle' ) ) );

		var makeSnippetRule = function ( label, pre, post ) {
			return {
				label: label,
				action: {
					type: 'encapsulate',
					options: {
						pre: pre,
						post: post
					}
				}
			};
		};

		var snips = {};
		if ( canNs === 'Module' ) {
			snips = {
				main: makeSnippetRule( 'Module body',
					'--[=[\nModule description\n]=]\n\nlocal p = {} --p stands for package\n\n--[=[\nFunction docs\n]=]\nfunction p.function_name(frame)\n\t',
					'\nend\n\nreturn p\n' ),
				getargs: makeSnippetRule( 'Import getArgs',
					'local getArgs = require(\'Module:Arguments\').getArgs' ),
				usegetargs: makeSnippetRule( 'Use getArgs on frame',
					'local args = getArgs(frame)' ),
				yesno: makeSnippetRule( 'Import Yesno',
					'local yesno = require(\'Module:Yesno\')' ),
				kvinpairs: makeSnippetRule( 'for k, v in pairs()',
					'for k, v in pairs(',
					') do\n\t\nend\n' )
			};

			if ( isTestcases ) {
				snips.testcases = makeSnippetRule( 'Module test cases',
					'local p = require(\'Module:UnitTests\')\n\nfunction p:test_something()\n\tself:preprocess_equals_many(\'{{' + '#invoke:' + moduleName + '|FUNCTION_NAME|\', \'}}\', {\n\t\t{\'INPUT1\', \'EXPECTED1\'},\n\t})\nend\n\nreturn p\n',
					'' );
			}
		} else if ( canNs === 'Module_talk' ) {
			if ( isTestcases ) {
				snips.testcasesInvoke = makeSnippetRule( 'Invoke testcases',
					'{{' + '#invoke: ' + moduleName + '/testcases | run_tests}}',
					'' );
			}
		}

		if ( !$.isEmptyObject( snips ) ) {

			wikiEditor( 'addToToolbar', {
				section: 'main',
				groups: {
					list: {
						tools: {
							props: {
								label: 'Common snippets',
								type: 'select',
								list: snips
							}
						}
					}
				}
			} );
		}
	};

	window.wsutils.wikiEditorConfigIncantation( addModuleTemplates );

// eslint-disable-next-line no-undef
}( mediaWiki, jQuery ) );