[go: up one dir, main page]

Jump to content

User:NguoiDungKhongDinhDanh/AceForLuaDebugConsole.js

From Meta, a Wikimedia project coordination wiki

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.
/**
 * This script adds Ace editor to the horrible-looking #mw-scribunto-input.
 * In my opinion, whoever designed it to be a plain <textarea> needs to
 * seriously reconsider their decision.
 * 
 * Use Ctrl + Alt then:
 * * Enter to run
 * * Backspace to clear
 * * Comma to retrieve previous version
 * * Dot to retrieve next version
 *
**/
/* jshint maxerr: 9999, undef: true, unused: true, quotmark: single */
/* globals $, mw, ace */

$(function() {
	if (
		mw.config.get('wgPageContentModel') !== 'Scribunto' ||
		!['edit', 'submit'].includes(mw.config.get('wgAction'))
	) {
		return;
	}
	
	mw.loader.using(['ext.codeEditor', 'mediawiki.user']).then(function() {
		var $textarea = $('#mw-scribunto-input');
		var $clear = $textarea.closest('fieldset').find(' > div:last-child > input');
		var $div = $('<div>').insertBefore($textarea).css({
			width: '100%',
			height: 500,
			lineHeight: '20px' // Same as .wikiEditor-ui .ace_editor
		});
		
		var editor = ace.edit($div[0], {
			mode: 'ace/mode/lua',
			showGutter: true
		});
		var session = editor.getSession();
		
		function setEditor() {
			session.setValue($textarea.val());
		}
		function setTextarea() {
			$textarea.val(session.getValue());
		}
		
		// Same as .wikiEditor-ui .ace_editor
		editor.setFontSize(13);
		
		// A hook for [[:en:User:Nardog/CodeEditorAssist.js]].
		// Unfortunately this is not possible with mw.hook.
		var CEASettings = JSON.parse(mw.user.options.get('userjs-codeeditorassist-settings'));
		
		if (CEASettings) {
			editor.setOptions(CEASettings);
		}
		
		$textarea.css('display', 'none');
		$textarea.on('change', setTextarea).trigger('change');
		
		$div.on('keydown', function(e) {
			if (!e.ctrlKey || !e.altKey) {
				return;
			}
			switch (e.keyCode) {
				case 8:
					$clear.click();
					break;
				case 13:
				case 188:
				case 190:
					setTextarea();
					$textarea.trigger(e.keyCode === 13 ? e : {
						type: 'keydown',
						keyCode: e.keyCode - 150
					});
					// God knows why #mw-scribunto-input's hist() is async.
					setTimeout(setEditor, 0);
					break;
			}
		});
	});
});