Jump to content

Расширение:Гаджеты

From mediawiki.org
This page is a translated version of the page Extension:Gadgets and the translation is 32% complete.
Outdated translations are marked like this.
This extension comes with MediaWiki 1.18 and above. Таким образом, вам не нужно загружать его снова. Тем не менее, вы всё равно должны следовать другим инструкциям.
Справка по расширениям MediaWiki
Gadgets
Статус релиза: стабильно
Реализация MyWiki , Служебная страница , API
Описание Позволяет пользователям включать на их странице настроек гаджеты на основе JS, предоставляемые другими пользователями
Автор(ы) Daniel Kinzler (Duesentriebобсуждение)
Политика совместимости Снэпшоты выходят вместе с MediaWiki. Мастер не имеет обратной совместимости.
MediaWiki 1.19+
Лицензия GNU General Public License 2.0 или позднее
Скачать
README
Пример Wikimedia Commons: Gadget overview, user preferences (click "Gadgets"; you need to be logged in of course)
  • $wgGadgetsRepo
  • $wgSpecialGadgetUsageActiveUsers
Ежеквартальные загрузки 121 (Ranked 45th)
Использование общедоступными вики 4,529 (Ranked 177th)
П��реведите расширение Gadgets, если оно доступно на translatewiki.net
Проблемы Открытые задачи · Сообщить об ошибке

Расширение Гаджеты позволяет пользователям возможность выбирать "гаджеты" на основе JavaScript или CSS, которые предоставляют другие пользователи wiki.

Гаджеты состоят из JavaScript и/или CSS Сниппеты , расположенных на страницах в пространстве имен MediaWiki. Каждый гаджет определяется строкой в MediaWiki:Gadgets-definition, содержащей название и описание гаджета, а также список используемых им фрагментов JS и CSS (смотрите раздел Использование ниже).

Поскольку гаджеты находятся в пространстве имен MediaWiki (список, определяющий гаджеты, а также фактические фрагменты кода), редактировать код могут только системные администраторы (администраторы интерфейса с версии 1.32). This is as it should be: only users especially trusted by the wiki community should be able to edit JavaScript code used by other users since JavaScript can easily be used to hijack accounts or spy on people.

Установка

  • Скачайте и распакуйте файл(ы) в папку с названием Gadgets в вашей папке extensions/.
    Вместо этого разработчикам и соавторам кода следует установить расширение из Git, используя:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/Gadgets
  • Добавьте следующий код в конце вашего файла LocalSettings.php :
    wfLoadExtension( 'Gadgets' );
    
  • Yes Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.

Использование

Selection of some gadgets at the user preferences in de.wikipedia

Once MediaWiki:Gadgets-definition is created with at least one valid gadget, a new "Gadgets" section will be shown on Special:Preferences for all users. Users can enable the gadgets they would like to use there. An overview of gadgets currently defined by MediaWiki:Gadgets-definition is also rendered on Special:Gadgets, along with helpful links to the relevant localisation and script/style pages for easy creation or editing. Statistics about gadget preferences are available at Special:GadgetUsage.

Формат определения

Each line on the MediaWiki:Gadgets-definition page should start with a "*" (asterisk) character to define a gadget. The line takes the following format:

* mygadget [опции] | названия страниц

The first field ("mygadget" in the example) is the gadget's internal name. The label for the preferences page comes from an interface message page (MediaWiki:Gadget-mygadget) where the proper name and a short description can be written, which also allows wikitext markup to be used.

The internal name must begin with a basic Latin letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), and periods (.). The reason for this limitation is that the internal name must be valid as the name of an HTML form name, as MediaWiki interface message key, and as ResourceLoader module name.

Формат опций:

[ResourceLoader | опция1 | опция2 | ... опцияN]

The ResourceLoader flag is required unless the gadget contains only styles. Options that are "flags" only need to have their name written to be turned on. Options that need a value are followed by an equals sign and a comma-separated list of values. All whitespace is optional and may be omitted.

[ResourceLoader | myflag | mykey = value1, value2, value3 ]

Примеры:

* mygadget[ResourceLoader]|mygadget.js|mygadget.css

или

* mygadget[ResourceLoader|package]| mygadget.js | mygadget-Foo.js | mygadget-data.json | mygadget.css

или

* mygadget[ ResourceLoader | rights=foo, bar ] | mygadget.js | mygadget.css

Using Gadget Definition Namespace

Версия MediaWiki:
1.41

There are two ways to define gadgets depending on the $wgGadgetsRepoClass. If It is 'MediaWikiGadgetsDefinitionRepo' (the default value), the list of available gadgets is defined on MediaWiki:Gadgets-definition. In an alternative way, Gadget definitions are defined on pages in the Gadget definition namespace when $wgGadgetsRepoClass is set to 'GadgetDefinitionNamespaceRepo'. (On MediaWiki 1.39+, the value to use instead is '\\MediaWiki\\Extension\\Gadgets\\GadgetDefinitionNamespaceRepo'.)

The migration of existing gadget definitions is not yet supported, so you will lose previously defined gadgets after changing this option.

Creation of the Gadget definition:mygadget page and putting in it the below JSON code have the same effect as mygadget[ ResourceLoader | rights=foo, bar ] | mygadget.js | mygadget.css.

{
	"settings": {
		"rights": [ "foo", "bar" ],
		"default": false,
		"package": false,
		"hidden": false,
		"skins": [],
		"actions": [],
		"category": ""
	},
	"module": {
		"scripts": [ "mygadget.js" ],
		"styles": [ "mygadget.css" ],
		"datas": [],
		"peers": [],
		"dependencies": [],
		"messages": [],
		"type": ""
	}
}

In above example, the Gadget:Mygadget.js and the Gadget:mygadget.css are used.

Опции

Options
Имя Параметры Описание С
ResourceLoader Нет Marks gadget's scripts as compatible with Загрузчик ресурсов . 1.17 (r76527)
dependencies Разделённые запятой названия модулей These modules will be loaded before the scripts of this gadget execute. См. список модулей по умолчанию. 1.17 (r76639)
rights Разделённые запятой названия привилегий Make the gadget available (and visible in preferences) only to users who have the specified privileges. 1.18 (r85268)
hidden Нет Скрыть гаджет со страницы Настройки. Это может использоваться двумя способами:
  • Enable a gadget by default without the ability to disable (as a modular alternative to Common.js). Note that you need to add both: hidden | default to load a module for all users.
  • Gadgets that are not meant for end-users but rather are meant to be loaded by other gadgets. For example, to allow two gadgets to re-use the same internal code or to register the "core" part of a gadget that only loads on certain pages.
1.28
skins Разделённые запятой названия тем оформления Make the gadget available (and visible in preferences) only to users who use the specified skins. Before MediaWiki 1.32 it was taking into consideration the skin set in preferences for the user, not the current displayed one (like when adding ?useskin=monobook in the URL, задача T199478). Since 1.39, the ResourceLoader module is not registered on skins the gadget is unavailable on, so the gadget cannot be loaded on those skins as a dependency or using mw.loader.load() either (задача T236603).
Use of skins is a last resort, and should be restricted to specialized code. For example code which relies on DOM manipulation in the absence of standardized APIs and that cannot be implemented using Core modules.
1.19 (r100509)
actions Разделённые запятой названия действий Make the gadget available only on the specified page actions. E.g. actions = edit, history to load a gadget only while editing and on history pages.
Specifying edit action will also load it on action=submit. Invalid actions effectively disable the gadget since it can't be run anywhere.
1.38 (gerrit:747112)
categories Comma-separated category names Make the gadget available only on the specified categories. E.g. categories = Archived, Maintenance to load a gadget only on pages in the Category:Archived or Category:Maintenance. See also: Template gadgets . 1.42 (gerrit:1005092)
namespaces Comma-separated namespace numbers Make the gadget available only on the specified namespaces. E.g. namespaces = 0, 2 to load a gadget only in mainspace and user namespace. 1.41 (gerrit:624517)
contentModels Comma-separated content models Make the gadget available on pages with the given content models. E.g. contentModels = wikitext to load a gadget only on wikitext pages. 1.41 (gerrit:922062)
default Нет Enable the gadget by default for everyone (including IPs). Registered users can still disable it in their preferences. 1.18 (r85902)
package Нет Mark this gadget as packaged. Only the first JavaScript page will be executed in this mode. Other pages can be imported by using the require() function. This mode also enables the use of JSON pages, which cannot be included otherwise. 1.38
type styles (default for CSS-only gadgets) or general (default otherwise) Use styles for modules that only modify styling for elements already on the page (e.g. when customizing the skin, layout, or article content). It will cause the CSS files of the module to be included from the page HTML instead of being loaded via JavaScript. Подробнее см. ResourceLoader/Migration guide (users)#Gadget type.
Using styles will not load in any specified JavaScript files. For gadgets that modify styling for elements through both JavaScript and CSS, two individual gadget definitions are required.
1.28
peers Разделённые запятой названия модулей These CSS-only gadgets will be loaded with this gadget. These gadgets will be loaded before any dependencies, and their styles will be applied even if JavaScript is disabled. Подробнее см. ResourceLoader/Migration guide (users)#Gadget peers. 1.29
supportsUrlLoad Нет | true | false Make the gadget available to be loaded with the ?withgadget URL query parameter. 1.38
Removed options
Name Parameters Description Since Removed
top Нет Makes the gadget to be top-loaded. This should be used sparingly, but may be needed for some initialization stuff like registering plugins with VisualEditor. 1.22 (gerrit:75506) 1.29
requiresES6 None Allow use of ES6 syntax (ES2015) in the gadget. Enabling this means server-side syntax validation is skipped for the gadget. Any ES6-requiring gadgets are loaded together in a single web request, which isolates failures due to invalid or unsupported syntax to those gadgets only, without affecting other gadgets and MediaWiki software features. It is recommended to use a tool like ESLint to ensure only valid ES6 syntax is used. Conflicts with default. 1.40 (gerrit:758086) 1.42
targets desktop (по умолчанию), mobile или desktop, mobile Set the Загрузчик ресурсов target(s) for the gadget.
Do not use targets, instead use skins where absolutely necessary.
1.21 (gerrit:60954) 1.42

You can specify extra dependencies for your gadgets, for example:

* mygadget[ResourceLoader|dependencies=jquery.ui, jquery.effects.clip]|mygadget.js|mygadget.css

Here, we ask ResourceLoader to load modules jquery.ui and jquery.effects.clip with mygadget. Note that gadgets can't depend on scripts from pages, static files, or external URLs, only on modules already registered in ResourceLoader. To make a script from a page depend on another script from a page, each should be a gadget that registers itself as a module in ResourceLoader, then they can be made to have dependencies using the following syntax:

* childgadget[ResourceLoader|dependencies=ext.gadget.parentgadget]|childgadget.js

Чтобы включить гаджет по умолчанию, используйте «default»:

* mygadget[ResourceLoader|default|dependencies=mediawiki.util]|mygadget.js|mygadget.css

To make the gadget available only to users with appropriate permissions, set the rights option, for example:

* ImprovedDeletion [rights=delete] | ImprovedDeletion.js

It makes the gadget available only to users who can delete pages.

Note that restrictions are based on permissions, not user groups like administrators or bureaucrats.

Вот несколько реальных примеров:

* modrollback [ResourceLoader |rights=rollback] |modrollback.js
* geonotice [ResourceLoader |default |rights=viewmywatchlist] |geonotice.js
* Ajax_sysop [ResourceLoader |rights=patrol, rollback, markbotedits, delete]|Ajax_sysop.js


User rights

This extension adds two new user rights, gadgets-edit and gadgets-definition-edit, which by default aren't given to any group.

You can add the following in your LocalSettings.php to provide the appropriate permissions for users who are within the interface-admin group. Editing pages in the Gadget namespace requires the gadgets-edit right and editing pages in the Gadget definition namespace requires the gadgets-definition-edit right.

$wgGroupPermissions['interface-admin']['gadgets-edit'] = true;
$wgGroupPermissions['interface-admin']['gadgets-definition-edit'] = true;

Страницы

The remaining fields on the definition line refer to the JavaScript, CSS, or JSON source pages that make up the gadget module. These are stored in the MediaWiki namespace as interface messages (MediaWiki:Gadget-mygadget.js and MediaWiki:Gadget-mygadget.css in the example). The page names must end with ".css", ".js", or ".json" respectively.

A gadget can use any number of source pages, e.g.:

 * frobinator[ResourceLoader]|frob.js|frob.css|pretty.css
 * l33t[ResourceLoader]|l33t.js
 * foobar[ResourceLoader|package]|foo.js|bar.js|foobar-data.json

Please note that if your code contains strings that could be interpreted as wiki syntax (e.g., the signature code ~~~~), you may want to enclose your code into ‎<nowiki>...‎</nowiki> and put these tags in JavaScript or CSS comments so they're not interpreted when used.

See the first and last lines of MediaWiki:Gadget-externalsearch-bar.js for an example.

Разделы

The list of gadgets in MediaWiki:Gadgets-definition can be broken into sections using lines that start and end with two or more "=" (equals) characters, enclosing the name of a system message that defines the section's name, for example:

 == interface-gadgets ==
 ...
 == editing-gadgets ==
 ...

This would define two new sections, with the titles defined on the pages MediaWiki:Gadget-section-interface-gadgets and MediaWiki:Gadget-section-editing-gadgets.

See meta:Gadgets for gadgets that are popular in Wikimedia communities.

См. также