User:逆襲的天邪鬼/Twinkle-lzh/friendlytag.js

// // vim: set noet sts=0 sw=8:

(function($) {

/* **************************************** *** friendlytag.js: Tag module **************************************** * Mode of invocation:    Tab ("Tag") * Active on:             Existing articles; *                        all redirects * Config directives in:  FriendlyConfig */

Twinkle.tag = function friendlytag { // article/draft tagging if( !Morebits.wiki.isPageRedirect && ( ( mw.config.get('wgNamespaceNumber') === 0 || mw.config.get('wgNamespaceNumber') === 118 ) && mw.config.get('wgCurRevisionId') ) || ( Morebits.pageNameNorm === '維基大典:沙盒' ) ) { Twinkle.addPortletLink( Twinkle.tag.callback, "標", "friendly-tag", "標記條目" ); } };

Twinkle.tag.callback = function friendlytagCallback { var Window = new Morebits.simpleWindow( 630, 500 ); Window.setScriptName( "Twinkle" );

var form = new Morebits.quickForm( Twinkle.tag.callback.evaluate );

if (document.getElementsByClassName("patrollink").length) { form.append( {			type: 'checkbox',			list: [				{					label: '標記頁面為已巡查',					value: 'patrolPage',					name: 'patrolPage',					checked: Twinkle.getFriendlyPref('markTaggedPagesAsPatrolled')				}			]		} ); }

Window.setTitle( "條目维护標記" );

form.append({		type: 'div',		id: 'tagWorkArea',		className: 'morebits-scrollbox',		style: 'max-height: 28em'	});

form.append( { type:'submit' } );

var container = new Morebits.quickForm.element({ type: "fragment" });

// function to generate a checkbox, with appropriate subgroup if needed var makeCheckbox = function(tag, description) { var checkbox = { value: tag, label: ": " + description }; if (Twinkle.tag.checkedTags.indexOf(tag) !== -1) { checkbox.checked = true; }		switch (tag) { case "併": var otherTagName = "併"; checkbox.subgroup = [ {						name: 'mergeTarget', type: 'input', label: '目標：', },					{						name: 'mergeTagOther', type: 'checkbox', list: [ {								label: '用標記其他條目', checked: true, }						]					}				];				if (mw.config.get('wgNamespaceNumber') === 0) { checkbox.subgroup.push({						name: 'mergeReason',						type: 'textarea',						label: '合併理由（會附在條目的討論頁）：',						tooltip: '請填寫理由. '					}); }				break; case "文未準": checkbox.subgroup = {}; break; default: break; }		return checkbox; };

var checkboxes = []; $.each(Twinkle.tag.article.tags, function(tag, description) {		checkboxes.push(makeCheckbox(tag, description));	}); container.append({		type: "checkbox",		name: "articleTags",		list: checkboxes	});

// append any custom tags if (Twinkle.getFriendlyPref('customTagList').length) { container.append({ type: 'header', label: '自定義模板' }); container.append({ type: 'checkbox', name: 'articleTags', list: Twinkle.getFriendlyPref('customTagList') }); }

var $workarea = $(form).find("div#tagWorkArea"); var rendered = container.render; $workarea.empty.append(rendered);

// style adjustments $workarea.find("h5").css({ 'font-size': '110%' }); $workarea.find("h5:not(:first-child)").css({ 'margin-top': '1em' }); $workarea.find("div").filter(":has(span.quickformDescription)").css({ 'margin-top': '0.4em' });

// add a link to each template's description page $.each(Morebits.quickForm.getElements(form, "articleTags"), function(index, checkbox) {		var $checkbox = $(checkbox);		var link = Morebits.htmlNode("a", ">");		link.setAttribute("class", "tag-template-link");		link.setAttribute("href", mw.util.getUrl("Template:" +			Morebits.string.toUpperCaseFirstChar(checkbox.values)));		link.setAttribute("target", "_blank");		$checkbox.parent.append(["\u00A0", link]);	});

var result = form.render; Window.setContent( result ); Window.display;

// fake a change event on the sort dropdown, to initialize the tag list var evt = document.createEvent("Event"); evt.initEvent("change", true, true); };

Twinkle.tag.checkedTags = [];

Twinkle.tag.updateSortOrder = function(e) { var sortorder = e.target.value;

Twinkle.tag.checkedTags = e.target.form.getChecked("articleTags"); if (!Twinkle.tag.checkedTags) { Twinkle.tag.checkedTags = []; }

var container = new Morebits.quickForm.element({ type: "fragment" });

// function to generate a checkbox, with appropriate subgroup if needed var makeCheckbox = function(tag, description) { var checkbox = { value: tag, label: ": " + description }; if (Twinkle.tag.checkedTags.indexOf(tag) !== -1) { checkbox.checked = true; }		switch (tag) { case "併": var otherTagName = "併"; checkbox.subgroup = [ {						name: 'mergeTarget', type: 'input', label: '目標：', },					{						name: 'mergeTagOther', type: 'checkbox', list: [ {								label: '用標記其他條目', checked: true, }						]					}				];				if (mw.config.get('wgNamespaceNumber') === 0) { checkbox.subgroup.push({						name: 'mergeReason',						type: 'textarea',						label: '合併理由（會附在條目的討論頁）：',						tooltip: '請填寫理由. '					}); }				break; case "文未準": checkbox.subgroup = {}; break; default: break; }		return checkbox; };

var checkboxes = []; $.each(Twinkle.tag.article.tags, function(tag, description) {		checkboxes.push(makeCheckbox(tag, description));	}); container.append({		type: "checkbox",		name: "articleTags",		list: checkboxes	});

// append any custom tags if (Twinkle.getFriendlyPref('customTagList').length) { container.append({ type: 'header', label: '自定義模板' }); container.append({ type: 'checkbox', name: 'articleTags', list: Twinkle.getFriendlyPref('customTagList') }); }

var $workarea = $(e.target.form).find("div#tagWorkArea"); var rendered = container.render; $workarea.empty.append(rendered);

// style adjustments $workarea.find("h5").css({ 'font-size': '110%' }); $workarea.find("h5:not(:first-child)").css({ 'margin-top': '1em' }); $workarea.find("div").filter(":has(span.quickformDescription)").css({ 'margin-top': '0.4em' });

// add a link to each template's description page $.each(Morebits.quickForm.getElements(e.target.form, "articleTags"), function(index, checkbox) {		var $checkbox = $(checkbox);		var link = Morebits.htmlNode("a", ">");		link.setAttribute("class", "tag-template-link");		link.setAttribute("href", mw.util.getUrl("Template:" +			Morebits.string.toUpperCaseFirstChar(checkbox.values)));		link.setAttribute("target", "_blank");		$checkbox.parent.append(["\u00A0", link]);	}); };

// Tags for ARTICLES start here

Twinkle.tag.article = {};

// A list of all article tags, in alphabetical order // To ensure tags appear in the default "categorized" view, add them to the tagCategories hash below.

Twinkle.tag.article.tags = { '文白相雜': '文白相雜', '繁簡相雜': '繁簡相雜', '遷': '議遷', '併': '議併', '無據': '是文無引據', '文未準': '是文未準，須辨真偽、正文辭' };

Twinkle.tag.article.dispute = { '引據未準，須審讀': '引用的準確性無法核實', '需纂以維基碼': '需要維基化', '文辭未準，須辨真偽': '真實性存疑', '文中存纂者己見': '包含編者個人想法、原創研究等', '非中立': '中立性有問題' };

Twinkle.tag.callbacks = { main: function( pageobj ) { var params = pageobj.getCallbackParameters, tagRe, tagText = '', summaryText = '添加', tags = [], groupableTags = [], i, totalTags;

// Remove tags that become superfluous with this action var pageText = pageobj.getPageText.replace(/\{\{\s*([Nn]ew unreviewed article|[Uu]nreviewed|[Uu]serspace draft)\s*(\|(?:\{\{[^{}]*\}\}|[^{}])*)?\}\}\s*/g, "");

var addTag = function friendlytagAddTag( tagIndex, tagName ) { var currentTag = ""; if( tagName === '文白相雜' ) { pageText += '\n'; } else { currentTag += '\n'; tagText += currentTag; }

if ( tagIndex > 0 ) { if( tagIndex === (totalTags - 1) ) { summaryText += '與'; } else if ( tagIndex < (totalTags - 1) ) { summaryText += '、'; }			}

summaryText += ''; };

// Check for preexisting tags and separate tags into groupable and non-groupable arrays for( i = 0; i < params.tags.length; i++ ) { tagRe = new RegExp( '(\\{\\{' + params.tags[i] + '(\\||\\}\\})|\\|\\s*' + params.tags[i] + '\\s*=[a-z ]+\\d+)', 'im' ); if( !tagRe.exec( pageText ) ) { if( Twinkle.tag.multipleIssuesExceptions.indexOf(params.tags[i]) === -1 ) { groupableTags = groupableTags.concat( params.tags[i] ); } else { tags = tags.concat( params.tags[i] ); }			} else { Morebits.status.warn( '信息', '在頁面上找到…跳过' ); // don't do anything else with merge tags if (params.tags[i] === "merge" || params.tags[i] === "merge from" ||					params.tags[i] === "merge to") { params.mergeTarget = params.mergeReason = params.mergeTagOther = false; }			}		}

var miTest = /\{\{(multiple ?issues|article ?issues|mi)[^}]+\{/im.exec(pageText); var miOldStyleRegex = /\{\{(multiple ?issues|article ?issues|mi)\s*\|([^{]+)\}\}/im; var miOldStyleTest = miOldStyleRegex.exec(pageText);

tags = tags.concat( groupableTags );

tags.sort; totalTags = tags.length; $.each(tags, addTag);

// smartly insert the new tags after any hatnotes. Regex is a bit more // complicated than it'd need to be, to allow templates as parameters, // and to handle whitespace properly. pageText = pageText.replace(/^\s*(?:((?:\s*\{\{\s*(?:about|correct title|dablink|distinguish|for|other\s?(?:hurricaneuses|people|persons|places|uses(?:of)?)|redirect(?:-acronym)?|see\s?(?:also|wiktionary)|selfref|the)\d*\s*(\|(?:\{\{[^{}]*\}\}|[^{}])*)?\}\})+(?:\s*\n)?)\s*)?/i,				"$1" + tagText);

summaryText += ( tags.length > 0 ? '標記' : '' ) + '至文章';

// avoid truncated summaries if (summaryText.length > (254 - Twinkle.getPref('summaryAd').length)) { summaryText = summaryText.replace(/\[\]+\|([^\+)\]\]/g, "$1"); }

pageobj.setPageText(pageText); pageobj.setEditSummary(summaryText + Twinkle.getPref('summaryAd')); pageobj.setWatchlist(Twinkle.getFriendlyPref('watchTaggedPages')); pageobj.setMinorEdit(Twinkle.getFriendlyPref('markTaggedPagesAsMinor')); pageobj.setCreateOption('nocreate'); pageobj.save(function {			// special functions for merge tags			if (params.mergeReason) {				// post the rationale on the talk page (only operates in main namespace)				var talkpageText = "\n\n== 議與" + params.nonDiscussArticle + "合併 ==\n\n";				talkpageText += params.mergeReason.trim + "--~";

var talkpage = new Morebits.wiki.page("Talk:" + params.discussArticle, "將理由貼进討論頁"); talkpage.setAppendText(talkpageText); talkpage.setEditSummary('議將' + params.nonDiscussArticle +  +					'併' +  + params.discussArticle + '' +					Twinkle.getPref('summaryAd')); talkpage.setWatchlist(Twinkle.getFriendlyPref('watchMergeDiscussions')); talkpage.setCreateOption('recreate'); talkpage.append; }			if (params.mergeTagOther) { // tag the target page if requested var otherTagName = "merge"; if (tags.indexOf("merge from") !== -1) { otherTagName = "merge to"; } else if (tags.indexOf("merge to") !== -1) { otherTagName = "merge from"; }				var newParams = { tags: [otherTagName], mergeTarget: Morebits.pageNameNorm, discussArticle: params.discussArticle, talkDiscussionTitle: params.talkDiscussionTitle };				var otherpage = new Morebits.wiki.page(params.mergeTarget, "標記其他頁面（" +					params.mergeTarget + "）"); otherpage.setCallbackParameters(newParams); otherpage.load(Twinkle.tag.callbacks.main); }		});

if( params.patrol ) { pageobj.patrol; }	} };

Twinkle.tag.callback.evaluate = function friendlytagCallbackEvaluate(e) { var form = e.target; var params = {}; if (form.patrolPage) { params.patrol = form.patrolPage.checked; }

params.tags = form.getChecked( 'articleTags' ); params.group = form.group.checked; params.tagParameters = { notability: form["articleTags.notability"] ? form["articleTags.notability"].value : null };	// common to, , params.mergeTarget = form["articleTags.mergeTarget"] ? form["articleTags.mergeTarget"].value : null; params.mergeReason = form["articleTags.mergeReason"] ? form["articleTags.mergeReason"].value : null; params.mergeTagOther = form["articleTags.mergeTagOther"] ? form["articleTags.mergeTagOther"].checked : false;

// form validation if( !params.tags.length ) { alert( '必须选择至少一个標記！' ); return; }	if( ((params.tags.indexOf("merge") !== -1) + (params.tags.indexOf("merge from") !== -1) + (params.tags.indexOf("merge to") !== -1)) > 1 ) { alert( '请在、和中选择一个. 如果需要多次合併，请使用并用管道符分隔條目名（但在这种情形中Twinkle不能自动標記其他條目）. ' ); return; }	if( (params.mergeTagOther || params.mergeReason) && params.mergeTarget.indexOf('|') !== -1 ) { alert( '目前还不支持在一次合併中標記多个條目，与开启关于多个條目的讨论. 请不要勾选“標記其他條目”和/或清理“理由”框，并重试. ' ); return; }

Morebits.simpleWindow.setButtonsEnabled( false ); Morebits.status.init( form );

Morebits.wiki.actionCompleted.redirect = Morebits.pageNameNorm; Morebits.wiki.actionCompleted.notice = "標記完成，在几秒内刷新頁面";

var wikipedia_page = new Morebits.wiki.page(Morebits.pageNameNorm, "正在標記條目"); wikipedia_page.setCallbackParameters(params); wikipedia_page.load(Twinkle.tag.callbacks.main); }; })(jQuery);

//