Cozinha de ''gadgets''

Revision as of 11:10, 30 April 2020 by He7d3r (talk | contribs) (Created page with "Em geral, confira as convenções de codificação de JavaScript para escrever JavaScript compatível com o estilo do MediaWiki.")

Receba as boas-vindas à cozinha de gadgets. Este é um tutorial de como pode escrever e utilizar gadgets e scripts pessoais em JavaScript.

O que são scripts pessoais e gadgets?

O MediaWiki permite que todos escrevam código JavaScript público para alterar imediatamente o comportamento do software. Este código pode ser compartilhado com outros usuários. Este código localiza-se em páginas wikis.

  • A user script can be edited by the original author (if it is stored in the User: namespace) and by anyone with the "edituserjs" user-right (usually just interface administrators). The code is usually hosted on a sub page of your user page. Examples include: XTools/ArticleInfo.js and m:User:Hoo man/useful links.js. User scripts are similar to the personal JavaScript pages such as Special:MyPage/common.js, but they allow single code chunks to be shared with other users.
  • Um gadget é um script pessoal que foi "promovido" por um administrador de interface, adicionando-o à página MediaWiki:Gadgets-definition. Usuários registrados podem ativar gadgets na aba "Gadgets" de suas preferências de usuário. Os gadgets são criados e gerenciados por administradores de interface.
  • Para completude: Também há o siteJS localizado na página MediaWiki:Common.js. O JavaScript naquela página afeta todos os usuários e é executado automaticamente tanto para usuários registrados quanto para não registrados. Interface administrators can edit that page.

Se estiver executando sua própria cópia do MediaWiki, $wgAllowUserJs precisa estar ativado para que scripts de usuário funcionem, e a extensão [[Special:MyLanguage/Extension:Gadgets|]] precisa ser instalada para possibilitar a promoção de scripts individuais para o status de gadget. Para uma experiência de desenvolvimento melhor, certifique-se de que a extensão CodeEditor esteja instalada em sua wiki.

Write your first user script

In this section, you create an example user script which calculates the estimated reading time of a wiki page.

  1. Ensure you are logged in.
  2. Visit Special:MyPage/common.js. This page holds your personal JavaScript that is loaded on every page view (except for Special:Preferences).
  3. Either create the page or edit the page if it already exists.
  4. Copy the following six lines and paste these lines into the page:
var numWords = $("#mw-content-text > div").text().split(" ").length;
var headerWords = $("h1").text().split(" ").length;
var totalWords = numWords + headerWords;
var timeInMinutes = totalWords / 200;
var header = $("h1").text();
$("h1").text(header + " (it will take you " + timeInMinutes + " minutes to read this page)");
  1. Click "Publish changes".
  2. Go to any page. Look at the title.

This example user script is taken from ChickTech High School Kickoff 2017/Tasks . There are more examples for simple user scripts on that page.

Em geral, confira as convenções de codificação de JavaScript para escrever JavaScript compatível com o estilo do MediaWiki.

Developing user scripts and gadgets

This section lists resources which are either needed or helpful for non-simple user scripts.

ResourceLoader

Since 2015 (MediaWiki 1.26), gadgets must use ResourceLoader (phab:T107399). Resource Loader is a core feature of MediaWiki that intelligently delivers JavaScript and CSS assets to users and readers. Because Gadgets are coded in JavaScript, as a Gadget coder you're bound to interact with ResourceLoader.

Your gadget should load useful ResourceLoader modules.

OOUI

OOUI is a JavaScript library with user interface elements (for example pop-up windows) specifically for use in MediaWiki. The library can be used in gadgets.

MediaWiki Action API

See Special:MyLanguage/API for more information.

If your gadget uses the MediaWiki API, add the "?callback=?" parameter to the API URL if you are trying to make an API request that would violate the same-origin policy (e.g. making a request to the Commons API from Wikipedia). This triggers the use of JSONP and enforces certain restrictions.

VisualEditor

See VisualEditor/Gadgets for a tutorial specifically for VisualEditor gadgets.

Debugging user scripts and gadgets

Privacy and external content

You should not load external resources that may harm users privacy. In Wikimedia wikis, the following domains are considered safe:

  • *.wiktionary.org
  • *.wikimedia.org
  • *.wikibooks.org
  • *.wikisource.org
  • *.wikisource.org
  • *.wikiversity.org
  • *.wikinews.org
  • *.wikiquote.org
  • *.wikidata.org
  • *.wikivoyage.org
  • www.mediawiki.org
There is a Jenkins job (job, code) to automatically check gadgets for this principle.

A more complex user script example

Check out MediaWiki:Tutorial-QuickRC.js which uses mw.loader, mw.util, mw.html, mw.user from ResourceLoader, the MediaWiki Action API, a jQuery UI dialog, jQuery AJAX, and jQuery event binding.

Copy and paste the contents of MediaWiki:Tutorial-QuickRC.js into your Special:MyPage/common.js.

The result should be the same as above, but now you can modify the script, play with it, and replace it with something else entirely.

Clicking "Preview" (or using the keyboard shortcut, typically Shift+Alt+P) in the editor will also execute the latest version of the script. This is a good way to iterate without saving the page. Remember, nothing is saved until you press "Publish page".

Load an existing user script

In the previous section, you copied the content of a user script. In this section, you will load the existing script MediaWiki:Tutorial-QuickRC.js instead.

  1. Ensure you are logged in.
  2. Visit Special:MyPage/common.js. This page holds your personal JavaScript that is loaded on every page view (except for Special:Preferences).
  3. Either create the page or edit the page if it already exists.
  4. Copy the following text and paste it into the page:
    mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript');
  5. Click "Publish changes". You should now have a link in the "Tools" section called "Quick changelog".
  6. Click "Quick changelog". You get a pop-up window. It shows you a subset of the recent changes on this website.

Use a script on another Wikimedia wiki

If you want to use a script on another Wikimedia website (for example English Wikipedia instead of MediaWiki.org), you perform the same steps as above: you tell ResourceLoader to load your code. Visit your common.js on English Wikipedia, and add the following:

mw.loader.load("//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript");

You can also load the user script which you just created above, by changing MediaWiki:Tutorial-QuickRC.js in the previous line to User:YourName/YourScript.js (replace YourName and YourScript accordingly). This first requires that you do not store the code of your user script in Special:MyPage/common.js itself but instead in a separate sub page of your user page.

This also helps to keep code in one single place, so you have to update code in only one place.

Disadvantages and problems of gadgets

  • Gadgets are developed by community members. As of today, there is no formal code review required for gadgets on Wikimedia sites (see phab:T71445). Please follow the best practices listed on this page.
  • On Wikimedia sites, the process how to "promote" a user script to a gadget in the "Gadgets" tab of the user preferences is not always clear. You will have to find an interface administrator and might have to provide deployment instructions to them.
  • Wikimedia lacks a systematic process for re-using, modifying and contributing to existing user scripts and gadgets.

Ideas what to work on

If you want to write features that directly help Wikimedia community members, see:

Deploying or enabling a gadget

If your user script should become a gadget (see the definitions above) on a wiki, the following steps are needed:

  • Steps for the user script author:
    • Recruit an experienced developer to review your gadget code. There is no formal process to do so.
    • Check with community members if there aren't any concerns with enabling the gadget on a wiki. For the website MediaWiki.org itself, this would be Project:Current_issues.
    • Recruit a site administrator with interface rights. See the page Special:ListUsers/interface-admin on your wiki.
  • Steps for the interface administrator:
    • Copy your JS & CSS files in the MediaWiki: namespace on your wiki, and make sure the page names have the prefix Gadget-.
      Example: MediaWiki:Gadget-userfeedback.js
    • Define the gadget on the MediaWiki:Gadgets-definition page of your wiki. That includes the modules used, dependencies, JS, and CSS file names, etc. This will allow users to enable the gadget on the Special:Preferences page of your wiki.
      Example: userfeedback[ResourceLoader|default|dependencies=ext.eventLogging]|userfeedback.js|userfeedback.css
    • Create a page for the gadget in the MediaWiki: namespace with prefix Gadget-. This will generate a label for the gadget on the Special:Preferences page of your wiki.
      Example: MediaWiki:Gadget-userfeedback
In the future, changes to ResourceLoader ("Gadgets 2.0") will make managing gadgets simpler.