MediaWiki:Gadget-Dicas.js

Nota: Depois de publicar, poderá ter de contornar a cache do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer / Edge: Pressione Ctrl enquanto clica Recarregar, ou pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
/** Provides some tips for editors
 * @see: Source code of the page http://code.google.com/hosting/createProject
 * @see: [[w:en:User:Cameltrader/Advisor]]
 */
/*jslint browser: true, white: true, regexp: true, continue: true*/
/*global jQuery, mediaWiki */
( function ( mw, $ ) {
'use strict';

var    pageName = mw.config.get( 'wgPageName' ).replace(/_/g, ' '),
	titleParts = pageName.split( '/' ),
	wgBookName = titleParts[0] || mw.config.get( 'wgPageName' ),
	tips=[],
	tipsList = '';

wgBookName = wgBookName.split( ':', 2 ).join( ':' );

mw.config.set( {
	'tipsMaxTitleParts': 5,
	'tipsHelpPage': 'Wikilivros:Diálogos comunitários'
} );
mw.messages.set( {
	'tips-ask':
		'Precisa de ajuda?',
	'tips-help':
		'Caso seja necessário, entre em contato com outros editores' +
		' através dos <a href="$1">diálogos comunitários</a>',
	'tips-all-uppercase-question': 'Tem certeza de que todas as' +
		' letras de "$1" precisam ser maiúsculas?',
	'tips-words-whitelist': '3D África AJAX APL AVL Bernoulli BIOS Blender Brasil C C++ CSS' +
		' Debian Dedekind Deus DNA DOS DVD EC3 Egito ERP Euclides Europa' +
		' EXT2 EXT3 EXT4 Fourier FreeBSD Freud GAS GeoGebra GIMP GNOME GNU' +
		' GNU-Linux Google GPL GUI HD Holanda HTML IDEs II III Japão' +
		' JavaScript KDE Knoppix Lanka LPIC MediaWiki MySQL Niterói Paulo' +
		' PCN PEAR PHP PostgreSQL RSS SGBDs Sol SQLite Sudão TV UMM' +
		' Wikilivros XML XVII XX XXI',
	'tips-all-lowercase-question': 'Tem certeza de que todas as' +
		' letras de "$1" precisam ser minúsculas?',
	'tips-first-uppercase-question': 'Tem certeza de que a' +
		' primeira letra de "$1" precisa ser maiúscula?',
	'tips-sentence-case':
		'Confira se usou maiúsculas e minúsculas de forma adequada no' +
		' título desta página. $1 Aqui no Wikilivros' +
		' os títulos das páginas são escritos assim: \n<ul>' +
		'<li>Livro de exemplo</li>\n' +
		'<li>Livro de exemplo/Capítulo de exemplo</li>\n' +
		'<li>Livro de exemplo/Uma SIGLA no título do capítulo</li>\n' +
		'<li>Livro de exemplo/Um Nome Próprio no título</li></ul>\n' +
		' A regra é usar sempre letras minúsculas, exceto na primeira letra' +
		' de nomes próprios e das palavras que aparecem depois de uma barra,' +
		' bem como nas siglas.',
	'tips-search-before-creating-a-new-book':
		'Antes de começar a escrever um novo livro, confira se não existe' +
		' algum livro sobre este assunto:\n<ul>' +
		' <li>Utilize a <a href="$2">página de buscas</a></li>' +
		' <li>Consulte a <a href="$1">biblioteca do Wikilivros</a></li></ul>' +
		'Se já houver um texto, pode ser melhor ajudar a aprimorá-lo,' +
		' em vez de criar um novo texto didático a partir do zero.',
	'tips-new-wikibook':
		'Se pretende começar a escrever um livro-texto chamado "$1", siga' +
		' <a href="$2">nossas convenções de' +
		' nomenclatura</a> e coloque:<ul>' +
		'<li>O índice nesta página (se precisar de um exemplo,' +
		' <a href="$3">clique aqui</a>)</li>' +
		'<li>O conteúdo dos capítulos em páginas com títulos da forma' +
		' "$1/Nome do capítulo"</li></ul>',
	'tips-too-many-bars':
		'O título desta página possui $1 barras. Não seria melhor' +
		' simplificá-lo para algo como "$2" ou "$3"?<br>No Wikilivros' +
		' as barras são usadas como separadores entre:\n<ul>' +
		'<li>O nome de um livro e o nome de um de seus capítulos;</li>' +
		'<li>O nome de um capítulo e o nome de um de seus subcapítulos.</li></ul>' +
		' A maioria dos wikilivros do projeto possui um número pequeno de' +
		' capítulos e por isso costuma ser suficiente usar apenas uma ou' +
		' duas barras em cada título.',
	'tips-deprecated-html':
		'Esta página contém pelo menos um dos seguintes códigos HTML que' +
		' foram depreciados: $1. É preciso substituí-los por opções equivalentes' +
		' que sejam válidas (clique nos links para obter sugestões)',
	'tips-numeric-title':
		'Pode ser melhor alterar o nome deste capítulo para algo mais' +
		' explicativo do que "$1", pois:\n<ul>' +
		'<li>Os links da barra de navegação ficarão mais intuitivos' +
		' para o leitor</li>' +
		'<li>Isso poderá aumentar a visibilidade da página nos mecanismos' +
		' de busca (da wiki, do Google, do Yahoo, do Bing, etc)</li></ul>',
	'tips-index-without-auto-cat':
		'Todas as páginas do livro devem ser categorizadas com a predefinição' +
		' AutoCat. Veja um exemplo:<br>' +
		' <code>{' + '{AutoCat|Tema|Sub-tema|Sub-sub-tema}}</code>',
	'tips-auto-cat-without-cat':
		'Complete a categorização deste índice, incluindo pelo menos um' +
		' tema na predefinição AutoCat. Veja um exemplo:<br>' +
		' <code>{' + '{AutoCat|Tema|Sub-tema|Sub-sub-tema}}</code>',
	'tips-chapter-without-auto-cat':
		'Todas as páginas do livro devem ser categorizadas com a' +
		' predefinição AutoCat. Para isso, basta colocar' +
		' <code>{' + '{AutoCat}}</code> depois do texto.',
	'tips-index-without-book-data':
		'Falta incluir a ficha deste livro para que ele seja posicionado' +
		' adequadamente nas seções da biblioteca. Para detalhes consulte' +
		' a página da <a href="$1">Predefinição:Ficha do livro</a>.'
});

function getListOfTips() {
	var i, w, part, word, words, problem, first, temp,
		subPageName = titleParts[ titleParts.length - 1 ],
		pgText = $('#wpTextbox1').val(),
		numericTitle = /^(?:Aula|Lição|Capítulo|Exercício)?\s*(?:\d+[ªº]?|V|V?I{1,3}|IV|IX|(?:Primeir|Segund|Terceir|Quart)[oa]|Um|Dois|Três|Quatro)\s*(?:Aula|Lição|Capítulo|Exercício)?$/i,
		oldHTMLTags = /<(APPLET|BASEFONT|CENTER|DIR|FONT|ISINDEX|MENU|S|STRIKE|U)\b[^>]*>(.*?)<\/\1>/ig,
		AutoCat = /\{\{[Aa]utoCat/,
		emptyAutoCat = /\{\{[Aa]utoCat\}\}/,
		bookData = /\{\{[Ff]icha do livro/,
		isBookIndex = ( pageName === wgBookName ),
		isRedirect = ( pgText.indexOf( '#REDIR' ) > -1 ),
		htmlExamples = {
			'applet' : '<object>',
			'basefont' : '<span style="color:red;">Texto</span>',
			'center' : '<p style="text-align: center;">Texto</p>',
			'dir' : 'Em código wiki:\\n*Item 1\\n*Item 2\\n\\nEm HTML:\\n<ul>\\n\\t<li>Item 1</li>\\n\\t<li>Item 2</li>\\n</ul>',
			'font' : '<span style="color:red;">Texto</span>',
			'isindex' : '<input/>',
			'menu' : 'Em código wiki:\\n*Item 1\\n*Item 2\\n\\nEm HTML:\\n<ul>\\n\\t<li>Item 1</li>\\n\\t<li>Item 2</li>\\n</ul>',
			's' : '<span style="text-decoration:line-through;">Texto</span>',
			'strike' : '<span style="text-decoration:line-through;">Texto</span>',
			'u' : '<span style="text-decoration:underline;">Texto</span>'
		};
	for( i = 0; i < titleParts.length; i+=1 ){
		part = titleParts[ i ];
		words = part.split( ' ' );
		problem = false;
		for( w = 0; w < words.length; w+=1 ){
			word = words[ w ];
			first = word.charAt(0);
			if ( $.inArray( word, mw.msg( 'tips-words-whitelist' ).split( ' ' ) ) > -1 ) {
				continue;
			}
			if ( first.toUpperCase() === first ) {
				if( word.toUpperCase() === word ) {
					if( w > 0 && word.length > 1 ) {
						problem = ( part.toUpperCase() === part && part.length > 1 ) ? part : word;
						tips.push( mw.msg(
							'tips-sentence-case',
							mw.msg( 'tips-all-uppercase-question', problem )
						) );
						break;
					} /*else {
						// If the first word after a separator has
						// only one character, it should be upper case
					}*/
				} else {
					if( w > 0 ) {
						problem = word;
						tips.push( mw.msg(
							'tips-sentence-case',
							mw.msg( 'tips-first-uppercase-question', problem )
						) );
						break;
					} /*else {
						// The first letter of the word after a separator
						// should be in upper case
					}*/
				}
			} else {
				if( w === 0 && word.toLowerCase() === word ) {
					problem = ( part.toLowerCase() === part ) ? part : word;
					tips.push( mw.msg(
						'tips-sentence-case',
						mw.msg( 'tips-all-lowercase-question', problem )
					) );
					break;
				}
			}
		}
		if ( problem ) {
			break;
		}
	}
	if( isBookIndex ) {
		//The current page should be the index of a book
		if ( pgText === '' ) {
			//This is likely a new index, since it is empty
			tips.push( mw.msg( 'tips-search-before-creating-a-new-book',
				mw.util.getUrl( 'Wikilivros:Biblioteca/Ordem alfabética' ),
				mw.util.getUrl( 'Especial:Busca' ) +
					'?search=' + mw.util.rawurlencode( mw.config.get( 'wgTitle' ) ) +
					'&fulltext=1'
			) );
			tips.push( mw.msg( 'tips-new-wikibook',
				wgBookName,
				mw.util.getUrl( 'Wikilivros:Nomenclaturas' ),
				mw.util.getUrl( 'Wikilivros:Página índice' )
			) );
		} else {
			//This is likely an existing index
			if ( !isRedirect ) {
				if ( AutoCat.test(pgText) ) {
					if ( emptyAutoCat.test(pgText) ) {
						tips.push( mw.msg( 'tips-auto-cat-without-cat' ) );
					}
				} else {
					tips.push( mw.msg( 'tips-index-without-auto-cat' ) );
				}
				if ( !bookData.test(pgText) ) {
					tips.push( mw.msg( 'tips-index-without-book-data',
						mw.util.getUrl( 'Predefinição:Ficha do livro' )
					) );
				}
			}
		}
	} else {
		//The current page should be a (sub)chapter of a book
		if ( !isRedirect ) {
			if ( !AutoCat.test(pgText) ) {
				tips.push( mw.msg( 'tips-chapter-without-auto-cat' ) );
			}
		}
		if( titleParts.length > mw.config.get( 'tipsMaxTitleParts' ) ) {
			tips.push( mw.msg(  'tips-too-many-bars',
				titleParts.length,
				titleParts[0] + '/' + titleParts[titleParts.length-1],
				titleParts[0] + '/' + titleParts[1] + '/' + titleParts[titleParts.length-1]
			) );
		}
		if ( numericTitle.test(subPageName) ){
			//The current title is not very descriptive
			tips.push( mw.msg( 'tips-numeric-title', subPageName ) );
		}
	}
	if( oldHTMLTags.test(pgText) ){
		// The page has deprecated HTML tags/attributes
		temp = [];
		$.each( htmlExamples, function(tag, replacement){
			temp.push( '<a href="javascript:alert(\'Experimente usar o seguinte:\\n\\n' +
				mw.html.escape( replacement ) + '\');">' +
				mw.html.escape( '<' + tag + '>' ) + '</a>' );
		});
		tips.push( mw.msg( 'tips-deprecated-html', temp.join( ', ' ) ) );
	}
	tipsList = '<ul>\n<li>' + tips.join('</li>\n<li>') + '</li>\n</ul>\n';
}

function displayTips() {
	if( tips.length > 0 ){
		var	$box = $('<div class="tips-box mw-collapsible mw-collapsed">'),
			$header = $('<div id="tips-header" class="mw-collapsible-toggle">'),
			$content = $('<div id="tips-content" class="mw-collapsible-content">'),
			$elem = $( '#toolbar' );
		if (!$elem.length) {
			$elem = $( '#editform' );
		}
		$box.append( $header );
		$box.append( $content );
		$header.text( mw.msg( 'tips-ask' ) );
		$content.html( tipsList + '\n' + mw.msg( 'tips-help',
			mw.util.getUrl( mw.config.get( 'tipsHelpPage' ) )
		) );
		$elem.before( $box );
	}
	// Temporary hack...
	$( '.mw-collapsible' ).makeCollapsible();
}
if ( 0 === mw.config.get( 'wgNamespaceNumber' ) && ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) > -1 ) ) {
	$(function () {
		getListOfTips();
		displayTips();
	});
}

}( mediaWiki, jQuery ) );

// [[Categoria:Gadgets|Dicas.js]]
// [[Categoria:Scripts do Wikilivros|Dicas.js]]