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

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

(function($){

/* **************************************** *** twinklewarn.js: Warn module **************************************** * Mode of invocation:    Tab ("Warn") * Active on:             User talk pages * Config directives in:  TwinkleConfig */

Twinkle.warn = function twinklewarn { if ( Morebits.wiki.flow.relevantUserName ) { Twinkle.addPortletLink( Twinkle.warn.callback, "警告", "tw-warn", "警告或提醒用戶" ); }

// modify URL of talk page on rollback success pages if( mw.config.get('wgAction') === 'rollback' ) { var $vandalTalkLink = $("#mw-rollback-success").find(".mw-usertoollinks a").first; if ( $vandalTalkLink.length ) { $vandalTalkLink.css("font-weight", "bold"); $vandalTalkLink.wrapInner($(" ").attr("title", "如果合适，您可以用Twinkle在该用户对话页上做出警告. "));

var extraParam = "vanarticle=" + mw.util.rawurlencode(Morebits.pageNameNorm); var href = $vandalTalkLink.attr("href"); if (href.indexOf("?") === -1) { $vandalTalkLink.attr("href", href + "?" + extraParam); } else { $vandalTalkLink.attr("href", href + "&" + extraParam); }		}	} };

Twinkle.warn.callback = function twinklewarnCallback { if( Morebits.wiki.flow.relevantUserName === mw.config.get( 'wgUserName' ) &&			!confirm( '您將要警告自己！您確定要繼續嗎？' ) ) { return; }

var Window = new Morebits.simpleWindow( 600, 440 ); Window.setTitle( "警告、通知用戶" ); Window.setScriptName( "Twinkle" );

var form = new Morebits.quickForm( Twinkle.warn.callback.evaluate ); var main_select = form.append( {			type: 'field',			label: '選擇警告或通知類別',			tooltip: '選擇具體的警告模板. '		} );

main_select.append( { type: 'select', name: 'sub_group' } ); Twinkle.warn.callback.create_category;

form.append( {		type: 'input',		name: 'article',		label: '條目連結',		value:( Morebits.queryString.exists( 'vanarticle' ) ? Morebits.queryString.get( 'vanarticle' ) : '' ),		tooltip: '給模板中加入一個條目連結，可留空. '	} );

var more = form.append( { type: 'field', name: 'reasonGroup', label: '警告信息' } ); more.append( { type: 'textarea', label: '可選信息：', name: 'reason', tooltip: '理由或是附加信息' } );

var previewlink = document.createElement( 'a' ); $(previewlink).click(function{		Twinkle.warn.callbacks.preview(result); // |result| is defined below	}); previewlink.style.cursor = "pointer"; previewlink.textContent = '預覽'; more.append( { type: 'div', id: 'warningpreview', label: [ previewlink ] } ); more.append( { type: 'div', id: 'twinklewarn-previewbox', style: 'display: none' } );

more.append( { type: 'submit', label: '提交' } );

var result = form.render; Window.setContent( result ); Window.display; result.main_group.root = result; result.previewer = new Morebits.wiki.preview($(result).find('div#twinklewarn-previewbox').last[0]);

// We must init the first choice (General Note); var evt = document.createEvent( "Event" ); evt.initEvent( 'change', true, true ); result.main_group.dispatchEvent( evt ); };

// This is all the messages that might be dispatched by the code // Each of the individual templates require the following information: //  label (required): A short description displayed in the dialog //  summary (required): The edit summary used. If an article name is entered, the summary is postfixed with "on article", and it is always postfixed with ". $summaryAd" //  suppressArticleInSummary (optional): Set to true to suppress showing the article name in the edit summary. Useful if the warning relates to attack pages, or some such. Twinkle.warn.messages = { "非建設編輯": { "uw-vandalism1": { label: "毀文觀（提醒）", summary: "毀文觀（提醒）" },		"uw-vandalism2": { label: "毀文觀（警告）", summary: "毀文觀（警告）" },		"uw-vandalism3": { label: "毀文觀（最後警告）", summary: "毀文觀（最後警告）" },	},	"文法": { "uw-lzh1": { label: "非文言", summary: "非文言" },		"uw-lzh2": { label: "非文言（最後警告）", summary: "非文言（最後警告）" },		"uw-lzh-en": { label: "非文言（英文警告）", summary: "非文言/Not Classical Chinese（Warning）" },		"uw-lzh-en-2": { label: "非文言（英文最後警告）", summary: "非文言/Not Classical Chinese（Final Warning）" },		"uw-simp": { label: "簡體字", summary: "簡體字" },		"uw-blp": { label: "生不立傳", summary: "生不立傳" },	},	"態度": { "uw-sign": { label: "沒有簽名", summary: "簽名" },		"uw-civil1": { label: "不文明（提醒）", summary: "不文明（提醒）" },		"uw-civil2": { label: "不文明（警告）", summary: "不文明（警告）" },		"uw-editwar": { label: "編輯戰", summary: "編輯戰" },		"uw-baduserpage": { label: "表達政治或宗教的用戶框/用戶頁", summary: "政治、宗教用戶頁" }	}, };

Twinkle.warn.prev_article = null; Twinkle.warn.prev_reason = null;

Twinkle.warn.callback.create_category = function (e) { // worker function to create the combo box entries var createEntries = function( contents, container, wrapInOptgroup ) { // due to an apparent iOS bug, we have to add an option-group to prevent truncation of text // (search WT:TW archives for "Problem selecting warnings on an iPhone") if ( wrapInOptgroup && $.client.profile.platform === "iphone" ) { var wrapperOptgroup = new Morebits.quickForm.element( {				type: 'optgroup',				label: '可用模板'			} ); wrapperOptgroup = wrapperOptgroup.render; container.appendChild( wrapperOptgroup ); container = wrapperOptgroup; }

$.each( contents, function( itemKey, itemProperties ) {			var key = (typeof itemKey === "string") ? itemKey : itemProperties.value;

var selected = false; if( old_subvalue && old_subvalue_re.test( key ) ) { selected = true; }

var elem = new Morebits.quickForm.element( {				type: 'option',				label: ": " + itemProperties.label,				value: key,				selected: selected			} ); var elemRendered = container.appendChild( elem.render ); $(elemRendered).data("messageData", itemProperties); } );	};

// create the option-groups $.each( Twinkle.warn.messages, function( groupLabel, groupContents ) {		var optgroup = new Morebits.quickForm.element( { type: 'optgroup', label: groupLabel } );		optgroup = optgroup.render;		sub_group.appendChild( optgroup );		// create the options		createEntries( groupContents, optgroup, false );	} );

// 自訂警告 var optgroup2 = new Morebits.quickForm.element( {		type: 'optgroup',		label: '自定義警告'	} ); optgroup2 = optgroup2.render; sub_group.appendChild( optgroup2 ); createEntries( Twinkle.getPref("customWarningList"), sub_group, true ); };

Twinkle.warn.callbacks = { getWarningWikitext: function(templateName, article, reason, isCustom) { var text = "' + article;		}

if (reason && !isCustom) { // we assume that custom warnings lack a parameter text += "';

return text; },	preview: function(form) { var templatename = form.sub_group.value; var linkedarticle = form.article.value; var templatetext;

templatetext = Twinkle.warn.callbacks.getWarningWikitext(templatename, linkedarticle,			form.reason.value, form.main_group.value === 'custom');

form.previewer.beginRender(templatetext); },	main: function( pageobj ) { var text = pageobj.getPageText; var params = pageobj.getCallbackParameters; var messageData = params.messageData; var date = new Date;

var dateHeaderRegex = new RegExp( "^==+\\s*" + date.getUTCFullYear + "年" + (date.getUTCMonth + 1) + "月" +			"\\s*==+", 'mg' ); var dateHeaderRegexLast, dateHeaderRegexResult; while ((dateHeaderRegexLast = dateHeaderRegex.exec( text )) !== null) { dateHeaderRegexResult = dateHeaderRegexLast; }		// If dateHeaderRegexResult is null then lastHeaderIndex is never checked. If it is not null but // \n== is not found, then the date header must be at the very start of the page. lastIndexOf // returns -1 in this case, so lastHeaderIndex gets set to 0 as desired. var lastHeaderIndex = text.lastIndexOf( "\n==" ) + 1;

if( text.length > 0 ) { text += "\n\n"; }

if( messageData.heading ) { text += "== " + messageData.heading + " ==\n"; } else if( !dateHeaderRegexResult || dateHeaderRegexResult.index !== lastHeaderIndex ) { Morebits.status.info( '信息', '未找到當月標題，將建立新的' ); text += "== " + date.getUTCFullYear + "年" + (date.getUTCMonth + 1) + "月 " + " ==\n"; }		text += Twinkle.warn.callbacks.getWarningWikitext(params.sub_group, params.article,			params.reason, params.main_group === 'custom') + "--~";

if ( Twinkle.getPref('showSharedIPNotice') && Morebits.isIPAddress( mw.config.get('wgTitle') ) ) { Morebits.status.info( '信息', '加入共享IP說明' ); text += "\n"; }

// build the edit summary var summary; if( params.main_group === 'custom' ) { switch( params.sub_group.substr( -1 ) ) { case "1": summary = "提醒"; break; case "2": summary = "注意"; break; case "3": summary = "警告"; break; case "4": summary = "最後警告"; break; case "m": if( params.sub_group.substr( -3 ) === "4im" ) { summary = "唯一警告"; break; }					summary = "提示"; break; default: summary = "提示"; break; }			summary += "：" + Morebits.string.toUpperCaseFirstChar(messageData.label); } else { summary = messageData.summary; if ( messageData.suppressArticleInSummary !== true && params.article ) { summary += "，於" + params.article + ""; }		}		summary += Twinkle.getPref("summaryAd");

pageobj.setPageText( text ); pageobj.setEditSummary( summary ); pageobj.setWatchlist( Twinkle.getPref('watchWarnings') ); pageobj.save; }, };

Twinkle.warn.callback.evaluate = function twinklewarnCallbackEvaluate(e) { var userTalkPage = 'User_talk:' + Morebits.wiki.flow.relevantUserName;

// Find the selected element so we can fetch the data structure var selectedEl = $(e.target.sub_group).find('option[value="' + $(e.target.sub_group).val + '"]');

// Then, grab all the values provided by the form var params = { reason: e.target.reason.value, main_group: e.target.main_group.value, sub_group: e.target.sub_group.value, article: e.target.article.value, // .replace( /^(Image|Category):/i, ':$1:' ),  -- apparently no longer needed... messageData: selectedEl.data("messageData") };

Morebits.simpleWindow.setButtonsEnabled( false ); Morebits.status.init( e.target );

Morebits.wiki.actionCompleted.redirect = userTalkPage; Morebits.wiki.actionCompleted.notice = "警告完成，將在幾秒後重新載入";

var wikipedia_page = new Morebits.wiki.page( userTalkPage, '用戶對話頁修改' ); wikipedia_page.setCallbackParameters( params ); wikipedia_page.setFollowRedirect( true ); wikipedia_page.load( Twinkle.warn.callbacks.main );

}; })(jQuery);

//