跳转到内容

User:SolidBlock/edittools.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
function makeButton($textbox, label, action) {
	var button = new OO.ui.ButtonInputWidget({label: label, tabIndex: 7});
	button.$element.click(function (element) {
		var text = $textbox.val();
		text = action(text);
		$textbox.val(text);
	});
	return button;
}

function append_buttons($editButtons) {
	$textbox = $('textarea#wpTextbox1');
	var append = function(label, action) {
		$editButtons.append(makeButton($textbox, label, action).$element);
	};
	
	append('替换{{.w}}', text => text
		.replace(/\{\{nowrap (begin|end)\}\}/g, '')
		.replace(/\{\{[\.·•]w\}\}\s*/g, '\n* ')
		.replace(/(list\d+\s*=\s*)(\[\[)/g, '$1\n* $2'));
	append('去除常见的多余链接颜色指定', text => text
		.replace(/<span\s+style=\"?color\:\s*\#000001;?\"?>(.*?)<\/span>/g, '$1')
		.replace(/<font\s+color\=\s*\"?\#?000001\"?>(.*?)<\/font>/g, '$1')
		.replace(/\{\{\s*color\s*\|\s*#000001\s*\|(.*?)\}\}/g, '$1')
		.replace(/\{\{\s*font\s*\|\s*color\=\s*#000001\s*\|(.*?)\}\}/g, '$1')
		.replace(/\[\[(.+?)\|(.+?)\]\]/g, (full, x, y) => (x == y ? '[[' + x + ']]' : '[[' + x + '|' + y + ']]')));
		
	append('替换<center>和<small>以及过时属性(仅限表格)', text => text.replace(
		/.+/g, row => {
			var styles = [];
			var originalRow = row;
			var attrsAffected = false;
			if (row.search(/\|\s*<center>/g) >= 0) {
				row = row.replace(/\|\s*<center>/g, '|').replaceAll('</center>', '');
				styles[styles.length] = 'text-align: center; ';
			}
			if (row.search(/\|\s*<small>/g) >= 0) {
				row = row.replace(/\|\s*<small>/g, '|').replaceAll('</small>', '');
				styles[styles.length] = 'font-size: smaller; ';
			}
			row = row.replace(/^\|\s*([^|]*?)\s*\|/, attrs => {
				attrsAffected = true;
				var original = attrs;
				attrs = attrs.replace(/\bwidth\s*=\s*([0-9a-z\%]+|\".*?\")/g, (full, capture) => {
					var capture = capture.replaceAll('"', '');
					if (capture.match(/^[\d]+$/)) {
						capture = capture + 'px';
					}
					styles[styles.length] = 'width: ' + capture + '; ';
					return '';
				});
				
				attrs = attrs.replace(/\bvalign\s*=\s*\"?(\w+)\"?/, (full, capture) => {
					styles[styles.length] = 'vertical-align: ' + capture + '; ';
					return '';
				});
				attrs = attrs.replace(/\balign\s*=\s*\"?(\w+)\"?/, (full, capture) => {
					styles[styles.length] = 'text-align: ' + capture + '; ';
					return '';
				});
				
				if (styles.length == 0) return original;
				if (attrs.search(/style\s*=\s*\"/) >= 0) {
					return attrs.replace(/(style\s*=\s*\")/, '$1' + styles.join(''));
				} else {
					return attrs + ' styles="' + styles.join('') + '"|';
				}
			});
			return attrsAffected ? row : originalRow;
		}));
}

$(function() {
	append_buttons($('.editButtons'));
});