MediaWiki:Common.js

Wikipedia'as/is

Fuomáš: Maŋŋel go almmuhat, soaitá leat dárbbašlaš sihkkut neahttalohkkii gaskaráju vai oainnat rievdadusaid. 

  • Firefox / Safari: Doala Shift dan botta go deattát Reload, dahje deaddil Ctrl-F5 dahje Ctrl-R (⌘-R Mac'as)
  • Google Chrome: Deaddil Ctrl-Shift-R (⌘-Shift-R Mac'as)
  • Internet Explorer / Edge: Doala Ctrl dan botta go deattát Álggat ođđasit, dahje deaddil Ctrl-F5
  • Opera: deaddil Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */

/* Check if external link targets exists **************************************
 *
 * Description: Make external iw-links red through styling and make them blue again if they exists
 * Maintainers: [[User:Jeblad]]
 */
 
(function(mw, $){
    if (!mw.config.get( 'wgIsArticle' )) return;
    if (mw.config.get( 'wgNamespaceNumber' ) != 0) return;
    if (!/^(view)$/.test(mw.config.get( 'wgAction' ))) return;

    var found = 0;
    for (var x in mw.config.get('wgCategories')) {
        if (mw.config.get('wgCategories')[x] == 'IW-check' && ++found) break;
    }
    if (!found) return;

    var api = '//%%.wikipedia.org/w/api.php';
    var languages = { 'nn' : {}, 'no' : {}, 'sv' : {}, 'da' : {} };
    //var lang = 'se';
    var numtitles = 50;
    var maxtitles = 2000;
    var query = {
        'action': 'query',
        'prop' : 'info',
        'format': 'json',
        'maxage': 15*60,
        'smaxage': 24*60*60
    };

    $(function(){
        var iwcheck = $('.iwcheck').find('a.extiw');
        if (!iwcheck || !iwcheck.length) return;
        for (var x in languages) {
            languages[x].titles = {},
            languages[x].found = 0;
        }
        iwcheck.each(function(i, el){
            if (el.title) {
                var matches = el.title.match(/^(.*?):(.*)$/);
                if (matches.length == 3 && languages[matches[1]] != undefined) {
                    languages[matches[1]].titles[matches[2]] = true;
                    languages[matches[1]].found++;
                }
            }
        });
        var plang = $('#p-lang');
        for (var x in languages) {
            if (!languages[x].found) continue;
            if (x === mw.config.get('wgLanguageCode')) continue;
            var a = [];
            for (var y in languages[x].titles)
                if (languages[x].titles[y]) a.push(y);
            var a = a.slice(0, maxtitles);
            for (var i = 0; i < a.length; i+=numtitles) {
                var titles = a.slice(i, (i+numtitles<a.length ? i+numtitles : a.length)).join('|');
                $.ajax({
                    url: api.replace(/%%/, x),
                    dataType: 'jsonp',
                    data: jQuery.extend({'titles': titles, requestid: x}, query),
                    cache: true,
                    context: document.body,
                    success: function(data, textStatus){

                        if (textStatus === null && textStatus != 'success') {
                            alert('Success, but with "' + textStatus + '"');
                            return;
                        }

                        // this shouldn't happen
                        if (!languages[data.requestid] && !languages[data.requestid].found) return;

                        var a = [];
                        for (var x in data.query.pages) {
                            if (x<0) continue;
                            if (languages[data.requestid].titles[data.query.pages[x].title])
                                a.push('[title="' + data.requestid + ':' + data.query.pages[x].title + '"]');
                        }
                        iwcheck.filter(a.join(',')).addClass('exist');
                    }
                });
            }
        }
    });
})(mediaWiki, jQuery);


/* Adapt a list structure and use it as a navigational aid **************************************
 *
 * Description: Gives a list some additional structuring and a collapse/expand functionality
 * Maintainers: [[User:Jeblad]]
 */
 
// build an opaque function object
(function(mw, $){
 
    // get the locally stored objects, clear out the objects on errors
    var max = 128;
    var values = {};
    try {
        values = JSON.parse( localStorage.getItem("navbox-items-value") || '{}' );
    }
    catch (e) {
        localStorage.setItem("navbox-items-value", '{}' );
    }
 
    // private method for local storage
    function store(key, idx, state) {
        // only check whats the state
        if (state === undefined)
            return (values[key] ? values[key][idx] : null);
        // build a copy where we start with our value and skip any later duplicates
        var obj = {};
        obj[key] = [];
        obj[key][idx] = state;
        var count = 0;
        for (var x in values) {
            if (x === key) {
                if (!obj[x]) obj[x] = [];
                for (var y in values[x])
                    if (!obj[x][y])
                        obj[x][y]=values[x][y];
            }
            else
                obj[x]=values[x];
            if (max<count++)
                continue;
        }
        values = obj;
        // rebuild indexes for local storage
        var a = [];
        for (var x in values) {
            var b = [];
            for (var y in values[x])
                b.push('"'+values[x][y]+'"');
            a.push('"'+x+'":['+b.join(',')+']');
        }
        window.localStorage.setItem("navbox-items-value", '{'+a.join(',')+'}' );
        // return our set state
        return state;
    }
 
    // worker process
    $(function() {
        // cache our navboxes
        var navbox = $('div.statbox');
        // we're running so remove no-script class
        navbox
        .removeClass('no-script');
        // identify lead ins
        navbox
        .find('dd')
        .find('ul,ol')
        .each(function(i, el) {
            var obj = el.previousSibling;
            while (obj && !/\S/.test(obj.nodeValue))
                obj = obj.previousSibling;
            if (obj)
                $(el)
                .addClass('lead-in');
        });
        // is collapsible navigation enabled?
        if (mw.config.get('wgVectorEnabledModules') && mw.config.get('wgVectorEnabledModules')['collapsiblenav']) {
            // identify collapsible navigations
            navbox
            .addClass('collapsible');
            // identify collapsed state and set up handlers
            navbox
            .find('dt')
            .each(function(i, el){
                var obj = el.nextSibling;
                while (obj && obj.nodeType != 1)
                    obj = obj.nextSibling;
                if (obj && obj.nodeName) {
                    $(el)
                    .addClass(function(index, currentClass){
                        var matches = $(el).closest('.navbox').attr('class').match(/navbox-([-\w]+)/);
                        var idx = $(this).closest('dl').prevAll('dl').length; // not sure 
                        if (matches && 1<matches.length && store(matches[1], idx) == 'expanded') {
                            $(el)
                            .nextUntil('dt')
                            .css('display', 'block');
                            return 'expanded';
                        }
                        else return 'collapsed';
                    })
                    .wrapInner('<span class="title"/>')
                    .click(function(){
                        var matches = $(this).closest('.navbox').attr('class').match(/navbox-([-\w]+)/);
                        var idx = $(this).closest('dl').prevAll('dl').length; // not sure 
                        $(this)
                        .closest('dt')
                        .toggleClass('collapsed expanded')
                        .each(function(i, el){
                            if (matches && 1<matches.length)
                                store(matches[1], idx, $(el).hasClass('collapsed') ? 'collapsed' : 'expanded');
                        })
                        .nextUntil('dt')
                        .slideToggle();
                    });
                }
            });
        }
    });
})(mediaWiki, jQuery);


// dynamic linkage to sami giellatekno
importScript('MediaWiki:Giellatekno.js');
 
/**
 * Description: Modify parts of the toolbar to better suit this projects needs
 * Maintainer:
 */
(function(mw, $) {

  // function to build complete labels, just to get rid of some pesky errors
    var label = function (msg, txt, before, after) {
        var str = '';
        if (before === undefined ? true : before) str += "{" + "{";
        str += msg;
        if (after === undefined ? true : after) str += "}" + "}";
        if (txt) str += " – " + txt;
        return str;
    };
 
    // function to build pre-parts of the templates, just to get rid of some pesky errors
    var pre = function (msg, txt, before) {
        var str = '';
        if (before === undefined ? true : before) str += "{" + "{";
        str += msg;
        if (txt) str += txt;
        return str;
    };
 
    // function to build peri-parts of the templates, just to get rid of some pesky errors
    var peri = function (msg, txt, before, after) {
        var str = '';
        if (before === undefined ? true : before) str += "{" + "{";
        str += msg;
        if (txt) str += txt;
        if (after === undefined ? true : after) str += "}" + "}";
        return str;
    };
 
    // get timestamp for templates
    var now = new Date();
    var timestamp = now.getUTCFullYear()
        + '-' + (now.getUTCMonth()<9 ? '0' : '') + (now.getUTCMonth()+1)
        + '-' + (now.getUTCDate()<9 ? '0' : '') + now.getUTCDate();
        
    // customization for the beta toolbar
    var customizeBetaToolbar = function () {

		// add quote signs to the format group in the main section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'main',
			'group': 'format',
			'tools': {
				'quote': {
					label: 'Aisttonmearka',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/a/ac/Norwegian_quote_sign.png',
					action: {
						type: 'encapsulate',
						options: {
							pre: "«",
							peri: "«»",
							post: "»"
						}
					}
				}
			}
		} );

		// add quote signs to the format group in the main section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'main',
			'group': 'format',
			'tools': {
				'link': {
					label: 'Liŋkaruođut',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/b/ba/Norwegian_link_sign.png',
					action: {
						type: 'encapsulate',
						options: {
							pre: "[[",
							peri: "[[]]",
							post: "]]"
						}
					}
				}
			}
		} );

		// add quote signs to the format group in the main section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'váldo',
			'group': 'hábmi',
			'tools': {
				'link': {
					label: 'Málleruođut',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/4/4a/Norwegian_template_sign.png',
					action: {
						type: 'encapsulate',
						options: {
							pre: "{{",
							peri: "{{}}",
							post: "}}"
						}
					}
				}
			}
		} );
        // add quote signs to the format group in the main section
    	$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'main',
			'group': 'format',
			'tools': {
				'link': {
					label: 'Mininalta-málle',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/6/6c/Wiki_letter_w.svg',
					action: {
						type: 'encapsulate',
						options: {
							pre: "",
							peri: "{{Mininalta}}",
							post: ""
						}
					}
				}
			}
		} );
 // add quote signs to the format group in the main section
        $( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'main',
			'group': 'format',
			'tools': {
				'link': {
					label: 'Nalta-málle',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/6/6c/Wiki_letter_w.svg',
					action: {
						type: 'encapsulate',
						options: {
							pre: "",
							peri: "{{Nalta}}",
							post: ""
						}
					}
				}
			}
		} );
		// add a article mark menu in the advanced section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'advanced',
			groups: {
				'bajilčála': {
					tools: {
						'bajilčála': {
							label: 'Merke',
							type: 'select',
							list: {
								'template-neutral' : {
									label: label('Neutralitehta', 'artihkal ii leat bealatkeahtes'),
									action: {
										type: 'encapsulate',
										options: {
											pre: pre('Neutralitehta', '|ts=' + timestamp + '|'),
											post: '}}',
											ownline: false
										}
									}
								},
								'template-accuracy' : {
									label: label('Dárkilvuohta', 'artihkal ii leat čállon dárkilvuođain'),
									action: {
										type: 'encapsulate',
										options: {
											pre: ('Dárkilvuohta', '|ts=' + timestamp + '|'),
											post: '}}',
											ownline: false
										}
									}
								},
								'template-nowrap' : {
									label: label('Dutkan', 'artihkkalis lea ođđa dutkama'),
									action: {
										type: 'encapsulate',
										options: {
											pre: pre('Dutkan', '|ts=' + timestamp + '|'),
											post: '}}',
											ownline: false
										}
									}
								},
								'template-spelling' : {
									label: '{{Gielladikšun}} – artihkkala giela galgá divvut',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{Gielladikšun|ts=' + timestamp + '|',
											post: '}}',
											ownline: false
										}
									}
								},
								'template-format' : {
									label: '{{Wikifiseren}} – artihkal gáibida wikifiserema',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{Wikifiseren|ts=' + timestamp + '|',
											post: '}}',
											ownline: false
										}
									}
								},
								'template-workinprogress' : {
									label: '{{Bargamin}} – artihkal lea barggu vuolde',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{Bargamin|ts=' + timestamp + '|',
											post: '}}',
											ownline: false
										}
									}
								}
							}
						}
					}
				}
			}
		} );



		// add a template menu in the advanced section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'advanced',
			groups: {
				'heading': {
					tools: {
						'heading': {
							label: 'Mállet',
							type: 'select',
							list: {
								'template-nowrap' : {
									label: '{{nowrap|…}} – hindre linjeskift i tekst og tall',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{nowrap|',
											post: '}}',
											ownline: false
										}
									}
								},
								'template-formatnum' : {
									label: '{{formatnum:…}} – tall med mellomrom og desimalkomma',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{formatnum:',
											post: '}}',
											ownline: false
										}
									}
								},
								'template-defaultsort' : {
									label: '{{DEFAULTSORT:…}} – olmmošartihkkaliid sirren goarggu mielde',
									action: {
										type: 'encapsulate',
										options: {
											pre: '{{DEFAULTSORT:',
											post: '}}',
											ownline: false
										}
									}
								}
							}
						}
					}
				}
			}
		} );

		// add a titles menu in the advanced section
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'advanced',
			groups: {
				'heading': {
					tools: {
						'heading': {
							label: 'Titlet',
							type: 'select',
							list: {
								'titles-links' : {
									label: '== Liŋkkat == – liŋkkat olggoldas neahttasiidduide',
									action: {
										type: 'encapsulate',
										options: {
											pre: '==Liŋkkat==',
											ownline: true
										}
									}
								},
								'titles-see-also' : {
									label: '== Geahča maid == – liŋkkat {{grammar:illativ|{{SITENAME}}}} dahje eará Wikimedia prošeavttaide',
									action: {
										type: 'encapsulate',
										options: {
											pre: '== Geahča maid ==',
											ownline: true
										}
									}
								},
								'titles-sources' : {
									label: '== Gáldut == – listu artihkkala gálduin',
									action: {
										type: 'encapsulate',
										options: {
											pre: '==Gáldut==',
											post: "\n<references />",
											ownline: true
										}
									}
								},
								'titles-sources' : {
									label: '== Čujuheamit == – čujuheamit artihkkala gálduide',
									action: {
										type: 'encapsulate',
										options: {
											pre: '== Čujuheamit ==',
											post: "\n<references />",
											ownline: true
										}
									}
								}
							}
						}
					}
				}
			}
        });
    };
 
    /* Check if we are in edit mode and the required modules are available and then customize the toolbar */
    if ($.inArray(mw.config.get('wgAction'), ['edit', 'submit']) !== -1 ) {
        mw.loader.using( 'user.options', function () {
            if ( mw.user.options.get('usebetatoolbar') ) {
    			mw.loader.using( 'ext.wikiEditor', function () {
    				$(customizeBetaToolbar);
    			});
    		}
    	});
    }
 
})(mediaWiki, jQuery);

/** Microsigns: endrer plassering av de små skiltene ******************** */

if (mw.config.get('wgArticleId')) {
	try {
		$( function() {
			var arr = Array();
			$('.microsign').each(function(i, el) { arr.push(el); });
			$('#bodyContent').append('<div id="microsigns"/>');
			var content = document.getElementById('microsigns');
			for (var x in arr) { content.appendChild(arr[x]); }
		});
	}
	catch (e) { /* just go away */ }
}

if (mw.config.get('wgUserName') && mw.config.get('wgArticleId')) {
	mw.loader.load('//commons.wikimedia.org/w/index.php?title=MediaWiki:Gadget-HotCat.js&action=raw&ctype=text/javascript');
}

/**
 * Description: Clean up the list of templates during ordinary article editing for base templates,
 * that is those with a leading dollar ($) sign in the name
 * Maintainers: [[User:Jeblad]]
 */
(function(mw, $) {
    if (mw.config.get( 'wgNamespaceNumber' ) != 10 && (mw.config.get( 'wgAction' ) == "edit" || mw.config.get( 'wgAction' ) == "submit")) {
        try {
            $(function() {
                var used = $('.templatesUsed');
                var expl = $('.mw-templatesUsedExplanation');
                var links = used.find('> ul > li > a').filter('[href*=":$"], [href*="MediaWiki:"]');
                if (links.length === 0) return;
                links.parent().css('display', 'none');
                expl.find('p').append(' (<a class="show-base-templates" href="#">Vis grunnmaler</a><a class="hide-base-templates" href="#">Skjul grunnmaler</a>)');
                expl.find('a.hide-base-templates').css('display', 'none');
                expl.find('a.show-base-templates').click(function(){
                    links.parent().css('display', 'list-item');
                    $(this).css('display', 'none');
                    $(this).parentsUntil('.mw-templatesUsedExplanation').find('.hide-base-templates').css('display', 'inline');
                    return false;
                });
                expl.find('a.hide-base-templates').click(function(){
                    links.parent().css('display', 'none');
                    $(this).css('display', 'none');
                    $(this).parentsUntil('.mw-templatesUsedExplanation').find('.show-base-templates').css('display', 'inline');
                    return false;
                });
            });
        }
        catch (e) {
          // Woopsie, die without a notice
        }
    }
})(mediaWiki, jQuery);

(function(mw, $) {
    var css = {
        'Láskkodiehtolista' : {
            'class' : 'horizontal-data-list'
        }
    }
    var categories = mw.config.get("wgCategories");
    for (var x in categories) {
        if (css[categories[x]]) {
            if (css[categories[x]].class)
                $('body').addClass(css[categories[x]].class);
            if (css[categories[x]].style)
                console.log('not implemented: failed attempt to set style');
        }
    }
})(mediaWiki, jQuery);

/* Enable interlanguage links to other Sami languages in Wikimedia Incubator.
 *
 * Maintainer: [[User:Jon Harald Søby (WMNO)]
 */

(function($) {
	$("span.gadget-iw-link a").prependTo("#p-lang .body ul").wrap("<li class='interlanguage-link interwiki-" + $("span.gadget-iw-link").attr("lang") + "'></li>");
})(jQuery);