Greasy Fork

WikiLang

Makes your preferred language links easy to find on Wikimedia pages. Config available via Script Commands.

目前为 2016-03-16 提交的版本。查看 最新版本

// ==UserScript==
// @name           WikiLang
// @namespace      mailto:[email protected]
// @author         Szop Gracz
// @description    Makes your preferred language links easy to find on Wikimedia pages. Config available via Script Commands.

// @require     https://openuserjs.org/src/libs/sizzle/GM_config.js
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_registerMenuCommand

// @include     *.wiki*.org/*
// @include     *.wiki*.org%2F*
// @include     *.wiktionary.org/*
// @include     *.wiktionary.org%2F*


// @version     1.0.7
// ==/UserScript==

/*
  This script may activate on pages that it is not made for, such as
  google search results pages (for example searching for
  ".wiktionary.org/" may trigger it). Although, even if it does activate,
  it should not do any harm, since it only modifies list items of very 
  specific classes. If You are concerned about running it on pages it is not
  designed for, You can replace the @inclide rules with the following, more
  strict, @match rules. Please note, that the @match rules below, will not
  allow this script to work on Google-cached Wikimedia pages or when accessing
  Wikimedia pages trough a web proxy.
*/

// @match       *://*.wikipedia.org/*
// @match       *://*.wiktionary.org/*
// @match       *://*.wikiquote.org/*
// @match       *://*.wikibooks.org/*
// @match       *://*.wikisource.org/*
// @match       *://*.wikinews.org/*
// @match       *://*.wikiversity.org/*
// @match       *://*.wikivoyage.org/*
// @match       *://*.wikidata.org/*


const langlist = ['- Select language -','Abkhazian','Achinese','Afar','Afrikaans','Akan','Albanian','Alemannisch','Amharic','Arabic','Aragonese','Aramaic','Armenian','Aromanian','Arpitan','Assamese','Asturian','Avaric','Aymara','Azerbaijani','Bambara','Banjar','BasaBanyumasan','Bashkir','Basque','Bavarian','Belarusian','Bengali','Bhojpuri','BikolCentral','Bishnupriya','Bislama','Bosnian','Breton','Buginese','Bulgarian','Burmese','Buryat','Cantonese','Catalan','Cebuano','CentralKurdish','Chamorro','ChavacanodeZamboanga','Chechen','Cherokee','Cheyenne','Chinese','Chinese(MinNan)','Choctaw','ChurchSlavic','Chuvash','ClassicalChinese','Colognian','Cornish','Corsican','Cree','Creek','CrimeanTurkish','Croatian','Czech','Danish','Divehi','Dutch','Dzongkha','EasternMari','EgyptianArabic','Emiliano-Romagnolo','English','Erzya','Esperanto','Estonian','Ewe','Extremaduran','Faroese','FijiHindi','Fijian','Finnish','French','Friulian','Fulah','Gagauz','Galician','GanChinese','Ganda','Georgian','German','Gilaki','GoanKonkani','Gothic','Greek','Guarani','Gujarati','Haitian','HakkaChinese','Hausa','Hawaiian','Hebrew','Herero','Hindi','HiriMotu','Hungarian','Icelandic','Ido','Igbo','Iloko','Indonesian','Interlingua','Interlingue','Inuktitut','Inupiaq','Irish','Italian','Japanese','Javanese','Kabardian','Kabyle','Kalaallisut','Kalmyk','Kannada','Kanuri','Karachay-Balkar','Kara-Kalpak','Kashmiri','Kashubian','Kazakh','Khmer','Kikuyu','Kinyarwanda','Komi','Komi-Permyak','Kongo','Korean','Kuanyama','Kurdish','Kyrgyz','Ladino','Lak','Lao','Latgalian','Latin','Latvian','Lezghian','Ligurian','Limburgish','Lingala','Lithuanian','Lojban','Lombard','LowGerman','LowSaxon(Netherlands)','LowerSorbian','Luxembourgish','Macedonian','Maithili','Malagasy','Malay','Malayalam','Maltese','Manx','Maori','Marathi','Marshallese','Mazanderani','MinDongChinese','Minangkabau','Mingrelian','Mirandese','Moksha','Moldovan','Mongolian','Nahuatl','Nauru','Navajo','Ndonga','Neapolitan','Nepali','Newari','Norfuk/Pitkern','NorthernFrisian','NorthernLuri','NorthernSami','NorthernSotho','Norwegian','NorwegianNynorsk','Nouormand','Novial','Nyanja','Occitan','OldEnglish','Oriya','Oromo','Ossetic','PalatineGerman','Pali','Pampanga','Pangasinan','Papiamento','Pashto','PennsylvaniaGerman','Persian','Picard','Piedmontese','Polish','Pontic','Portuguese','Punjabi','Quechua','Romani','Romanian','Romansh','Rundi','Russian','Rusyn','Sakha','Samoan','Samogitian','Sango','Sanskrit','Sardinian','SaterlandFrisian','Scots','ScottishGaelic','Serbian','Serbo-Croatian','Shona','SichuanYi','Sicilian','Silesian','SimpleEnglish','Sindhi','Sinhala','Slovak','Slovenian','Somali','SouthAzerbaijani','SouthernSotho','Spanish','SrananTongo','Sundanese','Swahili','Swati','Swedish','Tagalog','Tahitian','Tajik','Tamil','Tarantino','Taraskievica','Tatar','Telugu','Tetum','Thai','Tibetan','Tigrinya','TokPisin','Tongan','Tsonga','Tswana','Tumbuka','Turkish','Turkmen','Tuvinian','Twi','Udmurt','Ukrainian','UpperSorbian','Urdu','Uyghur','Uzbek','Venda','Venetian','Veps','Vietnamese','Volapuk','Voro','Walloon','Waray','Welsh','WestFlemish','WesternFrisian','WesternMari','WesternPunjabi','Wolof','WuChinese','Xhosa','Yiddish','Yoruba','Zazaki','Zeelandic','Zhuang','Zulu'];
const codelist = ['','ab','ace','aa','af','ak','sq','als','am','ar','an','arc','hy','roa-rup','frp','as','ast','av','ay','az','bm','bjn','map-bms','ba','eu','bar','be','bn','bh','bcl','bpy','bi','bs','br','bug','bg','my','bxr','zh-yue','ca','ceb','ckb','ch','cbk-zam','ce','chr','chy','zh','zh-min-nan','cho','cu','cv','zh-classical','ksh','kw','co','cr','mus','crh','hr','cs','da','dv','nl','dz','mhr','arz','eml','en','myv','eo','et','ee','ext','fo','hif','fj','fi','fr','fur','ff','gag','gl','gan','lg','ka','de','glk','gom','got','el','gn','gu','ht','hak','ha','haw','he','hz','hi','ho','hu','is','io','ig','ilo','id','ia','ie','iu','ik','ga','it','ja','jv','kbd','kab','kl','xal','kn','kr','krc','kaa','ks','csb','kk','km','ki','rw','kv','koi','kg','ko','kj','ku','ky','lad','lbe','lo','ltg','la','lv','lez','lij','li','ln','lt','jbo','lmo','nds','nds-nl','dsb','lb','mk','mai','mg','ms','ml','mt','gv','mi','mr','mh','mzn','cdo','min','xmf','mwl','mdf','mo','mn','nah','na','nv','ng','nap','ne','new','pih','frr','lrc','se','nso','no','nn','nrm','nov','ny','oc','ang','or','om','os','pfl','pi','pam','pag','pap','ps','pdc','fa','pcd','pms','pl','pnt','pt','pa','qu','rmy','ro','rm','rn','ru','rue','sah','sm','bat-smg','sg','sa','sc','stq','sco','gd','sr','sh','sn','ii','scn','szl','simple','sd','si','sk','sl','so','azb','st','es','srn','su','sw','ss','sv','tl','ty','tg','ta','roa-tara','be-x-old','tt','te','tet','th','bo','ti','tpi','to','ts','tn','tum','tr','tk','tyv','tw','udm','uk','hsb','ur','ug','uz','ve','vec','vep','vi','vo','fiu-vro','wa','war','cy','vls','fy','mrj','pnb','wo','wuu','xh','yi','yo','diq','zea','za','zu'];
const selector = 'LI.interlanguage-link.interwiki-';
const windowstyle = 'background-color: #d0e0ff;';
const iframestyle = 'height: 75%; max-height: 440px; top: calc(50% - 215px); width: 300px; left: calc(50% - 150px); border: 1px solid #000; border-radius: 4px; margin: 0px; opacity: 1; overflow: auto; padding: 0px; position: fixed; z-index: 9999; display: block; right: auto; bottom: auto;';

var settingsfields = 
{
	move_to_top:
	{
		section: ['General', 'Set how should the links be modified'],
		label: 'Move to top (refresh required after disabling)',
		labelPos: 'right',
		type: 'checkbox',
		default: true,
	},
	apply_style:
	{
		label: 'Apply style:',
		labelPos: 'right',
		type: 'checkbox',
		default: true,
	},
	style:
	{
		type: 'textarea',
		default: 'font-weight: bold;\nfont-size: 120%;',
	},
	langselect:
	{
		section: ['Language list', 'Choose which links to modify'],
		type: 'select',
		options: langlist,
		default: langlist[0],
	},
    add:
	{
        label: 'Add to list',
        type: 'button',
        click: function()
		{
			// I use getElementByID because I've experienced problems with builtin methods of accessing GM_Config fields
			var langs = document.getElementById('WikiLangConfig').contentWindow.document.getElementById('WikiLangConfig_field_languages').value;
			var newlang = GetLangCode(GM_config.fields['langselect'].toValue());
			if ( newlang == '' )
			{
				alert('Please select which language to add.');
				return;
			}
			if ( langs.split(' ').indexOf(newlang)<0 )
				document.getElementById('WikiLangConfig').contentWindow.document.getElementById('WikiLangConfig_field_languages').value = langs + (langs?' ':'') + newlang;
			else
				alert(GM_config.fields['langselect'].toValue() + ' (' + newlang + ')' + ' is already on the list.')
        },
    },
	languages:
	{
		type: 'text',
		default: 'en pl',
	},
};

GM_config.init(
{
	id: 'WikiLangConfig',
	title: 'WikiLang Settings',
	fields: settingsfields,
	events: 
	{
		save: function()
		{
			apply();
		},
	},
	css: '#WikiLangConfig { ' + windowstyle + ' } ',
});

function GetLangCode(LangName)
{
	var i = langlist.indexOf(LangName);
	return codelist[i<0?0:i];
}

function apply()
{
	GM_config.set('langselect',langlist[0]);
	
	const languages = GM_config.get('languages').split(' '); 
	const style = GM_config.get('style');

	var query_A = GM_getValue('query_A','');
	var A_selected;
	if(query_A)
	{
		A_selected = document.querySelectorAll(query_A);
		for ( var i=0; i<A_selected.length; ++i )
			A_selected[i].removeAttribute('style');
	}

	query_A = selector + languages[0] + ' > A';
	if ( GM_config.get('move_to_top') )
	{
		var query_LI = selector + languages[0];
		for ( var i=1; i<languages.length; ++i )
		{
			query_A = query_A + ', ' + selector + languages[i] + ' > A';
			query_LI = query_LI + ', ' + selector + languages[i];
		}
		const LI_selected = document.querySelectorAll(query_LI);
		var list = LI_selected[0].parentNode;
		for ( var i=LI_selected.length-1; i>=0; --i )
			list.insertBefore(LI_selected[i], list.childNodes[0]); // insert as first
	}
	else
	{
		for ( var i=1; i<languages.length; ++i )
			query_A = query_A + ', ' + selector + languages[i] + ' > A';
	}
	
	GM_setValue('query_A',query_A);
	
	if ( GM_config.get('apply_style') && typeof style == 'string' )
	{
		A_selected = document.querySelectorAll(query_A);
		for ( var i=0; i<A_selected.length; ++i )
			A_selected[i].setAttribute('style',style);
	}
}


function openconfig()
{
	GM_config.open();
	document.getElementById('WikiLangConfig').setAttribute('style',iframestyle);
}

apply();
GM_registerMenuCommand('WikiLang Settings', openconfig);