跳转到内容

User:Sicaral/Common-js

维基百科,自由的百科全书

/* 所有用戶在加載任何頁面時,這裡的JavaScript都會加載

辅助处理

[编辑]
*/
//功能設定
var JSConfig={
	'isEdit0':true, //设置是否显示编辑首段按钮
	'collapseText':'隐藏▲',//指示折叠收缩的默认文字
	'expandText':'显示▼',//指示折叠展开的默认文字
	'autoCollapse':2,  //文章少于 autoCollapse 个折叠块时,不自动折叠
	'SpecialSearchEnhancedDisabled':false//是否禁止增加其它搜索引擎
}
// 兼容性修正
if (window.showModalDialog && document.compatMode && document.compatMode == "CSS1Compat")
{
	var oldWidth;
	var docEl = document.documentElement;

	function fixIEScroll()
	{
		if (!oldWidth || docEl.clientWidth > oldWidth){
			doFixIEScroll();
		}else{
			setTimeout(doFixIEScroll, 1);
		}
		oldWidth = docEl.clientWidth;
	}

	function doFixIEScroll() {
		docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
	}

	document.attachEvent("onreadystatechange", fixIEScroll);
	attachEvent("onresize", fixIEScroll);
}

// 移動元素
function elementMoveto(node, refNode, pos){//默认位置为refNode前
	if(node && refNode){
		var parent=refNode.parentNode;
		if (pos && pos=='after') {refNode=refNode.nextSibling;}
		try {
			if(refNode){
				parent.insertBefore(node, refNode);
			}else{
				parent.appendChild(node);
			}
		} catch (DOMException) {};
	}
}
//创建元素
function createElement(tag,children,props){
	var element = document.createElement(tag);
	if(children instanceof Array){
		for(var i=0;i<children.length;i++){
			var child=children[i];
			if(typeof child=='string'){child=document.createTextNode(child);}
			if(child){element.appendChild(child);}
		}
	}
	if(typeof props=='object'){
		for(var k in props){
			switch(k){
			case 'styles':
				var styles=props.styles;
				if(typeof styles=='object'){
					for(var s in styles){element.style[s]=styles[s];}
				}
				break;
			case 'events':
				var events=props.events;
				if(typeof events=='object'){
					for(var e in events){element['on'+e]=events[e];}
				}
				break;
			case 'class':
				element.className=props[k];break;
			default:
				element.setAttribute(k,props[k]);
			}
		}
	}
	return element;
}
 
//导入模块
function getWikiPath(page,paras){
	paras.ctype=paras.ctype||'text';
	paras.dontcountme=paras.dontcountme||'s';
	paras.action=paras.action||'raw';
	var url = wgScriptPath + '/index.php?title=' + encodeURI( page.replace( ' ', '_' ) );
	for(var k in paras){url += '&' + k + '=' + paras[k]; }
	return url;
}
function importScript( page ) {
	var src= /^https?:\/\//.test(page) ? page : getWikiPath(page,{'ctype':'text/javascript'});
	var scriptElem = createElement( 'script',null,{'src':src,'type':'text/javascript'} );
	document.getElementsByTagName( 'head' )[0].appendChild( scriptElem );
}
function importStylesheet( page ) {
	var sheet= /^https?:\/\//.test(page) ? page : getWikiPath(page,{'ctype':'text/css'});
	var styleElem = createElement( 'style', ['@import "'+sheet+'";'], {'type':'text/css'} );
	document.getElementsByTagName( 'head' )[0].appendChild( styleElem );
}

/* 测试元素中是否含有指定的样式 **************************************
 * Description: 使用正则式与缓存来提高性能
 * Maintainers: User:fdcn @zh.wikipedia
 *              [[en:User:Mike Dillon]], [[en:User:R. Koot]], [[en:User:SG]] @en.wikipedia
 */
var hasClass = (function () {
	var reCache = {};
	return function (element, className) {
		return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
	};
 })();

//设置中文语言页
var htmlE=document.documentElement;
htmlE.setAttribute("lang",wgUserLanguage);
htmlE.setAttribute("xml:lang",wgUserLanguage);


/*

工具提示與快捷鍵

[编辑]
*/
ta = {};
ta['ca-article'] = ['a','浏览条目正文'];
ta['ca-nomove'] = ['','你不能移动这个页面'];
ta['n-Featured_articles']=['','查看中文维基百科的特色条目'];
ta['n-Featured_content']=['','查看中文维基百科的特色内容'];
ta['n-commonsupload'] = ['','把自由版权图片上传到维基共享资源'];
ta['n-contact'] = ['','如何联络维基百科'];
ta['n-villagepump'] = ['','参与维基百科社群的讨论'];
ta['n-Information_desk'] = ['','解答任何与维基百科无关的问题的地方'];
ta['n-conversion'] = ['','提出繁简体转换请求'];
ta['n-allpages'] = ['','浏览所有页面的清单'];
ta['ca-nstab-project'] = ['a','查看维基计划页面'];
/*

調整編輯工具欄

[编辑]
*/
//加載編輯工具功能
importScript('MediaWiki:Edittools.js');

//mwEditButtons , mwCustomEditButtons 为预设按钮訊息集合
function addEditButton(imageId, imageFile, tagOpen, sampleText, tagClose, speedTip){
	var item={
		"imageId": imageId,
		"imageFile": "/w/skins/common/images/" + imageFile,
		"tagOpen": tagOpen,
		"sampleText": sampleText,
		"tagClose": tagClose,
		"speedTip": speedTip
	};
	mwCustomEditButtons.push(item);
	if(imageId){mwCustomEditButtons[imageId]=item;}
	return item;
}

//define buttons 定義按鈕
var __temp;
addEditButton('btnInterLink','Internal_link_icon.png','[[','链接标题',']]','内部链接');
addEditButton('btnInterHashLink',"Button_sub_link.png", "[[条目#", "章节|文本", "]]", "内部段落链接");
addEditButton('btnCategoryLink',"Button_category02.png", "[[:Category:", "分类名", "]]", "分类链接");
addEditButton('btnMediaLink','Media_icon.png','[[Media:','Example.ogg',']]','媒体文件链接');
addEditButton('btnExtraLink','External_link_icon.png','[','http://www.example.com 链接标题',']','外部链接(加前缀 http://)');
addEditButton('btnTemplateLink',"Template_button.png", "{{", "模板名", "}}", "应用模板");
addEditButton('btnCategory',"Button_category03.png", "[[Category:", "分类名", "]]", "分类");
addEditButton('btnRedirect',"Button_redir.png", "#REDIRECT [[", "目标条目名", "]]", "重定向");
addEditButton('btnImage','Image_icon.png','[[Image:','Example.jpg',']]','嵌入图像');
addEditButton('btnAdvImage',
	"Button_advanced_image.png",
	"<imagemap>\n",
	"Image:圖像名 | 100px | 描述\nrect    0  0  50 50  [[鏈接]]\ncircle  50 50 20     [[鏈接B]]\ndesc bottom-left\n",
	"</imagemap>",
	"高级画像"
);
__temp="\nImage:PictureFileName.jpg|"+"图片题注";
addEditButton('btnGallery',"Btn_toolbar_gallery.png","<gallery>",__temp+__temp,"\n</gallery>","画廊");
addEditButton('btnMath','Math_icon.png','<math>','插入数学公式','</math>','插入数学公式(LaTeX)');
addEditButton('btnNowiki','Nowiki_icon.png','<nowiki>','插入非格式文本','</nowiki>','插入非格式文本');
addEditButton('btnSigOnly','Button_sig.png','~~\~','','','签名(无日期)');
addEditButton('btnSignature','Signature_icon.png','—~~\~~','','','签名');
addEditButton('btnHeadline2','Button_headline2.png','== ','标题文字',' ==','2级标题文字');
addEditButton('btnHeadline3',"Button_headline3.png", "=== ", "标题文本", " ===", "三级子标题" );
addEditButton('btnHr','H-line_icon.png','\n----\n','','','水平线');
addEditButton('btnBr',"Button_enter.png", "<br />", "", "", "换行");
addEditButton('btnBold','Bold_icon.png','\'\'\'','粗体','\'\'\'','粗体');
addEditButton('btnItalic','Italic_icon.png','\'\'','斜体','\'\'','斜体');
__temp="下划线";
addEditButton('btnUnderline','Button_underline.png','<span style="text-decoration: underline;">',__temp,'</span>',__temp);
__temp="删除线";
addEditButton('btnStrike',"Button_strike.png", "<del>",__temp, "</del>",__temp);
__temp="左对齐";
addEditButton('btnAlignLeft',"Button_align_left.png", '<div style="text-align: left;">\n',__temp, "\n</div>",__temp);
addEditButton('btnAlignCenter',"Button_center.png", '<div style="text-align: center;">\n', "居中", "\n</div>","居中");
__temp="右对齐";
addEditButton('btnAlignRight',"Button_align_right.png", '<div style="text-align: right;">\n',__temp, "\n</div>",__temp);
__temp="上标";
addEditButton('btnSup',"Button_sup_letter.png", "<sup>",__temp, "</sup>", __temp);
__temp="下标";
addEditButton('btnSub',"Button_sub_letter.png", "<sub>",__temp, "</sub>",__temp);
addEditButton('btnBig',"Button_big.png", '<span style="font-size:larger;">', "放大", "</span>", "放大");
__temp="缩小";
addEditButton('btnSmall',"Button_small.png", '<span style="font-size:smaller;">',__temp, "</span>",__temp);
addEditButton('btnShift',"Button_shifting.png", ":", "", "", "缩进" );
addEditButton('btnEnum',"Btn_toolbar_enum.png", "#", "", "", "数字列表" );
addEditButton('btnList',"Btn_toolbar_liste.png", "*", "", "", "符号列表" );
addEditButton('btnDefine',"Button_definition_list.png", "; ", "释义" , " : ", "定义文本" );
addEditButton('btnColor',"Button_font_color.png", '<span style="color: ColorName;">', "彩色文本", "</span>", "彩色文本");
addEditButton('btnQuote',"Button_blockquote.png", '{\{quote|\n', "引文", "\n}\}", "块引用");
addEditButton('btnCode',"Button_code.png", "<code>", "代码", "</code>", "代码文本");
addEditButton('btnSource',"Button_source.png", '<source lang="text">', "源代码", "<\/source>", "高亮代码");
addEditButton('btnComment',"Button_hide_comment.png", "<!-- ", "隐藏文字", " -->", "注释或隐藏文字");
addEditButton('btnTable',"Button_array.png",'\n{| border="1" \n|- \n| 第一部分 || 第二部分 \n|- \n| 第三部分 || 第四部分',"","\n|}\n", "插入表格");
__temp="参考";
addEditButton('btnRef', "Button_ref.png", "<ref>", __temp, "</ref>", __temp );
__temp="同项参考";
addEditButton('btnRef2', "Button_ref_adv.png", '<ref name="">', __temp, '</ref>', __temp  );
addEditButton('btnReferences', "Button_refs.png", '\n==参考文献==\n<div class="references-small">\n<references />\n</div>', '', '', "参考文献区"  );
delete __temp;

//設置寬度
mwCustomEditButtons['btnSigOnly'].width = 11;
mwCustomEditButtons['btnRef2'].width = 12;
//設置行編輯模式
mwCustomEditButtons['btnHeadline2'].doClick=
mwCustomEditButtons['btnHeadline3'].doClick=
mwCustomEditButtons['btnAlignLeft'].doClick=
mwCustomEditButtons['btnAlignCenter'].doClick=
mwCustomEditButtons['btnAlignRight'].doClick=
mwCustomEditButtons['btnShift'].doClick=
mwCustomEditButtons['btnEnum'].doClick=
mwCustomEditButtons['btnList'].doClick=
mwCustomEditButtons['btnDefine'].doClick=
function(pre,post,sampletext){insertLine(pre,sampletext,post,true);}

//增加下拉選單
$(function(){
	mwEditButtons=[];//清除原系統按鈕

	var menu=createDropdownMenu('条目编辑',"articleEdit","dropdownListEditTools");
	if(!menu) return;
	menu.add("外部链接章节","elink",
		"\n==外部链接==\n* [" , "网页地址 网页说明" , "]\n");
	menu.add("参见章节","seealso",
		"\n==参见==\n* [[" , "参见地址" , "]]\n");
	menu.add("小作品","stub",
		"\n{\{" , "" , "小作品}\}");
	menu.add("消歧义","Disambig",
		"\n'''{{PAGENAME}}'''可以指:\n" , "* [[歧义1]],描述1\n* [[歧义2]],描述2" , "\n{\{disambig}\}");
	menu.add("条目消歧义","otheruses",
		"{\{Otheruses|","条目名称|subject=本页主題描述|other=同名或類似名的其它條目描述","}\}");
	menu.add("正在编辑","inuse",
		"{\{Inuse}\}","","");
	menu.add("正在发生","Current",
		"{\{Current}\}","","");
	menu.add("合并本条目到","mergeto",
		"{\{mergeto|","合并本条目到的条目名称","}\}");
	menu.add("合并到本条目","mergefrom",
		"{\{mergefrom|","需要合并到本条目的条目名称","}\}");
	menu.add("分拆条目","split",
		"{\{Split}\}","","");
	menu.add("正在翻译","translation",
		"{\{translation|tfrom=","在此填入来源","|tpercent=翻譯進度百分數}\}");
	
	menu=createDropdownMenu('非中文标明',"langTags","dropdownListEditTools");
	if(!menu) return;
	menu.add("英语", "en", "{\{lang|en|","英语","}\}");
	menu.add("德语", "de", "{\{lang|de|","德语","}\}");
	menu.add("法语", "fr", "{\{lang|fr|","法语","}\}");
	menu.add("日语", "ja", "{\{lang|ja|","日语","}\}");
	menu.add("西班牙语", "es", "{\{lang|es|","西班牙语","}\}");
	menu.add("阿拉伯语", "ar", "{\{lang|ar|","阿拉伯语","|\u200E}\}");
	menu.add("俄语", "ru", "{\{lang|ru|","俄语","}\}");
	menu.add("希伯来语", "he", "{\{lang|he|","希伯来语语","|\u200E}\}");
	menu.add("希腊语", "el", "{\{lang|el|","希腊语","}\}");
	menu.add("其他语言", "langcode", "{\{lang|"+"在此填上语言代码|","其他语言","}\}");
});

// 調整工具
hookEvent("load",function(){
	var wpEditToolbar=document.getElementById("toolbar");
	if(!wpEditToolbar){return;}
	var dropdownListEditTools=document.getElementById('dropdownListEditTools');
	//移動下拉選單
	if(dropdownListEditTools){wpEditToolbar.appendChild(dropdownListEditTools);}

	//移動符號表
	var editspecialchars=document.getElementById("editpage-specialchars");
	elementMoveto(editspecialchars , wpEditToolbar , 'after' );
});

/*

增加特殊符號的下拉選單

[编辑]
*/
/**
 * add menu for selecting subsets of secial characters
 * must match MediaWiki:Edittools
 * Maintainers: User:fdcn @zh.wikipedia
 */
$(function(){
	var edittools = document.getElementById('editpage-specialchars');
	if (edittools) {
		// select subsection of special characters
		var lines = edittools.getElementsByTagName('p');
		function chooseCharSubset() {
			var s=menu.selectedIndex;
			for (var i = 0,p; p=lines[i] ; i++) {
				p.style.display = i == s ? 'inline' : 'none';
			}
		}

		var menu=createElement("select",null,{
			'styles':{'display':"inline"},
			'events':{'change':chooseCharSubset}
		});
		for (var i = 0,p; p=lines[i] ; i++) {
			menu.options[i]=new Option(p.title?p.title:p.id);
		}
		edittools.insertBefore(menu,edittools.firstChild);
		chooseCharSubset();
	}
});

/*

編輯首段

[编辑]
*/
//JSConfig.isEdit设置开关,对不需要编辑首段的页面,还可在页面中加&#123;{Noedit0}&#125;模板
if (wgIsArticle) {
	addOnloadHook(function(){
		if(!JSConfig.isEdit0||(document.getElementById&&document.getElementById('no-edit-0'))){return;}
		var caEdit=document.getElementById&&document.getElementById('ca-edit');
		if (!caEdit){return;}
		var link = createElement('A',['0'],{'href':caEdit.firstChild.href + '&section=0'});
		var id = 'ca-edit-0';
		ta[id] = ['0', '编辑首段'];
		var caEdit0 = createElement('LI',[link],{'id':id,'class':caEdit.className});
		caEdit.className = 'istalk';
		caEdit.parentNode.insertBefore(caEdit0,caEdit.nextSibling);
		//单独进行提示和快捷键处理
		updateTooltipAccessKeys([caEdit0]);
		akeytt(id);
	});
}

/*

取消修訂編輯摘要修正

[编辑]
*/
/**
 fix edit summary prompt for undo
 this code fixes the fact that the undo function combined with the "no edit summary prompter" causes problems if leaving the edit summary unchanged
 this was added by [[:en:User:Deskana]], code by [[:en:User:Tra]]
 */
$(function () {
	var autoSummary=document.getElementsByName('wpAutoSummary')[0];
	if (document.location.search.indexOf("undo=") != -1 && autoSummary)
	{
		 autoSummary.value='';
	}
})

/*

Special:Search其他搜尋引擎連結表單

[编辑]
*/
var searchEngines=[];
var createSearchForm;//可在用户皮肤JS中自行增加引擎。
function SpecialSearchEnhanced() 
{
	if (
		JSConfig.SpecialSearchEnhancedDisabled ||
		wgCanonicalNamespace != "Special" ||
		wgCanonicalSpecialPageName != "Search"
	){return;}
	if(skin == "monobook" || skin == "cologneblue" || skin == "simple"){
		var mainNode = document.getElementsByTagName("form")[0];
	}
	if (!mainNode) return;
	var searchbox=document.getElementById("lsearchbox");
	var div= createElement("div",null,{styles:{'width':"100%",'textAlign':'center'}});
	mainNode.appendChild(div);

	/**
	 * 建立一个搜索引擎
	 */
	createSearchForm=function(engine_name, engine_url, logo_url, search_action_url, 
	search_field_name, add_search_field, field_array, logo_width, logo_height)
	{
		var input=createElement("input",null,{'type':"hidden",'name':search_field_name})
		var inputs = [input];
		for( var k in field_array){
			inputs.push(createElement(
				"input",null,{'type':"hidden",'name':k,'value':field_array[k]}
			));
		}
		inputs.push(createElement(
			"input",null,{'type':"submit",'value':'搜索'}
		));
		var form = createElement("form",inputs,
			{
				'method':"get",
				'action':search_action_url,
				'styles':{'display':"inline"},
				'events':{'submit':function(){input.value = searchbox.value+add_search_field;}}
			}
		);
		
		var img = createElement("img",null,{
			'src':logo_url,
			'alt':engine_name,
			'styles':{'borderWidth':"0",'padding':"5px",'width':logo_width||'135px','height':logo_height||'35px'}
		});
		var a = createElement("a",[img],{'href':engine_url});
		var span= createElement("span",[form,a],{styles:{'marginRight':"1em"}});

		searchEngines.push(span);
		searchEngines[engine_name]=span;
		div.appendChild(span);
	}

	//於此開始列示各引擎。
	//google
	createSearchForm(
		"Google","http://www.google.com/",  
		"http://www.google.com/logos/powered_by_google_135x35.gif", 
		"http://www.google.com/search","q", "", 
		{"as_sitesearch": "zh.wikipedia.org"},
		"135px","35px"
	);		
	//live search
	createSearchForm(
		"Live", "http://search.live.com/",   
		"http://upload.wikimedia.org/wikipedia/zh/thumb/1/17/Mslivelogo.png/120px-Mslivelogo.png",
		"http://search.live.com/results.aspx","q", "",
		{"q1":"site:zh.wikipedia.org"},
		'120px','24px'
	);
	//yahoo
	createSearchForm(
		"Yahoo!", "http://www.yahoo.com/",  
		"http://upload.wikimedia.org/wikipedia/zh/thumb/a/ad/Yahoo_Logo.svg/120px-Yahoo_Logo.svg.png",
		"http://search.yahoo.com/search","p", "", 
		{"vs": "zh.wikipedia.org","ei":"UTF-8"},
		'135px','25px'
	);
}

addOnloadHook(SpecialSearchEnhanced); //啟動Search Engine