Jump to content

Расширение:Всплывающие окна

From mediawiki.org
This page is a translated version of the page Extension:Popups and the translation is 50% complete.
Для the feature that is powered by this extension, см.: Special:MyLanguage/Page Previews.
Справка по расширениям MediaWiki
Popups
Статус релиза: стабильно
Реализация Тема оформления
Описание Отображает всплывающие окна, когда пользователи наводят курсор на ссылки на статьи и маркеры сносок
Автор(ы)
MediaWiki 1.37+
PHP 5.6+
  • $wgPopupsVirtualPageViews
  • $wgPopupsTextExtractsIntroOnly
  • $wgPopupsStatsvSamplingRate
  • $wgPopupsRestGatewayEndpoint
  • $wgPopupsConflictingNavPopupsGadgetName
  • $wgPopupsPageDisabled
  • $wgPopupsHideOptInOnPreferencesPage
  • $wgPopupsGateway
Licence GNU General Public License 2.0 or later
Скачать
Пример English Wikipedia
Переведите расширение Popups, если оно доступно на translatewiki.net
Проблемы Открытые задачи · Сообщить об ошибке

Расширение PopupsSpecial:Version отображается как Previews) отображает предварительный просмотр страниц и ссылок при наведении курсора на ссылку на статью или, соответственно, на ссылку. Первый состоит из резюме содержания статьи, второй показывает полное содержание ссылки.

Это инициатива команды дизайнеров, вдохновленных популярным гаджетом Навигационные окошки. В настоящее время эта функция доступна во всех Википедиях по умолчанию для вышедших из системы пользователей. Описание функций расширения и дополнительную информацию о его использовании в проектах Викимедиа доступно в Page Previews.

The Reference Previews feature was added eventually and aims to fulfill a wish from the German-speaking community's Technical Wishlist. A more detailed description and more information on its use is available at Предпросмотры сносок .

Зависимости

Это расширение имеет жесткую зависимость от Расширение:TextExtracts и Расширение:PageImages при использовании по умолчанию со шлюзом mwApiPlain. Существуют также дополнительные необязательные зависимости от Расширение:EventLogging и Extension:WikimediaEvents (для инструментария).

Установка

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

Настройка

Параметр Значение по умолчанию Документация
$wgPopupsVirtualPageViews false Должно ли расширение регистрировать виртуальные просмотры страниц.
$wgPopupsHideOptInOnPreferencesPage false Whether the option to enable/disable Page Previews should be hidden on Preferences page.
$wgPopupsOptInDefaultState 1 (удалено в 1.43) Default Page Previews visibility for old accounts. Has to be a string as a compatibility with beta feature settings. Для получения более подробной информации см. T191888. Это значение внутренне преобразуется в булево значение. Therefore, a value greater than or equal to 2 has the same meaning as 1.
$wgPopupsOptInStateForNewAccounts 1 (удалено в 1.43) Default Page Previews visibility for newly created accounts (1.32-1.43). Для получения более подробной информации см. T191888.
$wgPopupsConflictingNavPopupsGadgetName 'Navigation_popups' The local Navigation popups gadget name used as its identifier in MediaWiki:Gadgets-definition . Этот гаджет несовместим с предварительным просмотром страниц. Это расширение будет отключаться для пользователей с включённым гаджетом.
$wgPopupsGateway 'mwApiPlain' Which gateway to use for fetching Popups data. Available options: mwApiPlain, restbasePlain, restbaseHTML. Full and always up to date list is available in src/gateway/page.js.
$wgPopupsRestGatewayEndpoint '/api/rest_v1/page/summary/' Specify a REST endpoint where summaries should be sourced from. Конечная точка должна соответствовать спецификации на Specs/Summary/1.2.0 . If using an external provider (e.g. for development), ensure $wgThumbnailStepsRatio and $wgThumbnailSteps are configured identically for the provider and MediaWiki instance to avoid rendering broken images.
$wgCiteReferencePreviews true Enables Reference Previews when the Расширение:Цитата is installed.
$wgCiteReferencePreviewsConflictingRefTooltipsGadgetName ReferenceTooltips Локальное название гаджета Всплывающие сноски , которое используется в качестве идентификатора в MediaWiki:Gadgets-definition . This gadget is incompatible with reference previews. Reference previews will disable themselves for users with the gadget enabled.
$wgPopupsStatsvSamplingRate 0 Sampling rate for logging performance data to statsv.
$wgPopupsPageDisabled Several special pages. See extension.json for the full list. Список страниц, на которых не следует отображать всплывающие окна. Включает подстраницы. These pages are subject to the HTML cache policy of the wiki. A purge on these pages may be needed to see the effect of this configuration variable. Every excluded page should be defined by a canonical name, eg: Special:Userlogin.

Содержимое предпросмотра страниц

Всплывающие окна предварительного просмотра страницы показывают изображение (если оно доступно) и небольшой фрагмент текста.

Изображение

Изображение формируется при помощи Расширение:PageImages , которое возвращает одну наиболее подходящую миниатюру, связанную со статьёй. Оно игнорирует шаблоны обслуживания, незавершённые статьи и т. д.

Текст

The page previews can be configured with any compatible API that is compatible with the Page content service summary endpoint using $wgPopupsRestGatewayEndpoint. For third parties we encourage using the Page Content Service to enjoy using Popups with your local wiki.

Вы также можете использовать расширение Расширение:TextExtracts . This extension has various caveats and we do not actively support use of this API.

Отрисовщики (рендереры)

This extensions currently has only one renderer, that is for ordinary pages.

New renderers for different kind of pages, or things like references can be easily added.

One needs to create a new object with the following methods:

  • init
  • createPopup
  • getOffset
  • getClasses
  • processPopup

You can see details of these methods in ext.popups.renderer.article.js or this patch that adds a renderer for references.

API предварительного просмотра страниц

Каждый проект уникален, и то, что отображается в превью, сильно зависит от содержимого вашей вики.

Расширение Popups оптимизировано для работы с контентом, подобным Википедии (например, викитекстом).

Если ваша вики использует другой тип обработчика содержимого (например, как в случае с Wikibase ) потребуется предоставить собственный API.

API может быть написан на любом языке, но ответ API должен соответствовать спецификации указанной на странице Specs/Summary/1.2.0 .

Определение новых API выходит за рамки расширения Popups.

После определения вы можете настроить предварительный просмотр страниц, чтобы они указывали на ваш API, используя параметр конфигурации $wgPopupsRestGatewayEndpoint.

Известные проблемы

  • Users of the Translate extension should note that Page Previews requests previews in the content language of the page. If the preview contains a complete translatable block, then it will be translated. If, however, the preview contains an incomplete translateable block – because a sentence is cut off, say – it isn't translated and will be displayed in the page's content language. If you are observing this behavior, consider marking up individual sentences in your lead section. T167852 is for a technical audience but has more information on the underlying problem.
  • Longer math formulas cutting off in preview - long math or chemical formulas (formulas wider than the preview width) display as truncated in previews. We were not able to add a gradient in order to indicate that the formula is continued on the article itself.
  • Small files may be in the "Рage information" (action=info), but not in the "Popups". Some requirements are set here - for a portrait image: exact (min) height 250 px & max width 203 px; for a landscape image: exact (min) width 320 px & max height 200 px[1]. To display, images must be able to become a thumbnail that is larger or equal to these "exact" sizes. (If you are cropping a large image to make a leading picture for an article, be sure that the picture you are creating is not smaller than the specified sizes.)
  • The preview popup for some pages may contain only the text: There was an issue displaying this preview. One of the reasons for this is the TextExtracts extension failing to find any "intro" text for the page, which can happen if the article begins with certain entities, such as an infobox created with the PortableInfobox extension. A work-around for this is to set $wgPopupsTextExtractsIntroOnly = false; although this can cause the preview to contain unwanted entities, such as the titles for non-intro sections. The TextExtracts configuration variable $wgExtractsRemoveClasses may then be used to clean up those unwanted entities from the preview, though this will also hide them from all other users of the TextExtracts API.

Расширяемость

In MediaWiki 1.40, extensions and skins can extend the page previews functionality with their own custom preview types.

It does this by registering a PluginModules attribute in its extension.json or skin.json file that points to a ResourceLoaderModule that can register a preview type.

{
    "attributes": {
        "Popups": {
            "PluginModules": [
              "skins.skinjson.popup"
            ]
        }
    }
}

The plugin module should export information about when the preview should be displayed (via selector), and how the preview data should be retrieved (via gateway library). The selector should match an element which has a data-title attribute. The data-title attribute will be passed to the fetchPreviewForTitle function.

module.exports = {
        // a unique ID representing your preview type.
        type,
        // CSS-селектор, который соответствует вашему собственному типу предварительного просмотра
        selector: '.mycustomselector',
        // Шлюз
        gateway: {
                fetchPreviewForTitle:  ( title, el ) => {
                	const deferred = $.Deferred();
                	deferred.resolve( {
                		title: 'Hello world',
                		extract: [
                			`Hi`
                		],
                		url: 'https://www.mediawiki.org/wiki/Extension:Popups',
                		type,
                		languageCode: 'en',
                		languageDirection: 'ltr',
                		thumbnail: undefined,
                		pageId: -1
                	} );
                	return deferred;
                }
        }
};

For real world examples, Расширение:Math provide smath tooltips and Расширение:Цитата provides reference previews.

ЧЗВ (FAQ)

Почему я не могу копировать и вставлять текст из предпросмотра?

At time of writing, the cons of doing so outweigh the pros. Essentially it boils down to decreasing the touch area to read the article in full. Once Page Previews is deployed on English and German Wikipedia, feel free to reopen this task and reignite the discussion, but right now we have no plans.

Как я могу изменить изображение, отображаемое в предпросмотре?

См. Расширение:PageImages#Выбор изображения.

Как я могу удалять содержимое из предпросмотра страницы?

Any element marked with the noexcerpt class will be stripped from the summary.

Почему содержимое удалено из краткого содержания?

Любой HTML-элемент, отмеченный классами noexcerpt, mw-ref, reference, noprint, nomobile или sortkey, будет удалён из краткого содержания. If the text should be displayed in the summary, you should under no circumstances use these classes in any templates that are used within the beginning section of an article.

Откуда берутся краткие содержания?

These are provided by the summary REST API (Wikimedia production wikis) or the TextExtracts API in case your wiki is using the default mwApiPlain gateway.

Почему фразы в скобках удалены?

There's a good discussion going on in T91344 in Phabricator. If you have any views on this or see any problems relating to this, please let us know.

Почему я не вижу всплывающие окна вне основного пространства имён?

Popups appear on links to pages in content namespaces only. This is a limitation of Popups; TextExtracts are available from other namespaces. You may work around this by appending more namespaces into $wgContentNamespaces .

Ссылки

Developers quick start

The quickest way (last updated March 2026) to set up Popups is to install Extension:MobileFrontendContentProvider and to add the following code to LocalSettings.php

Visiting localhost/wiki/Paris should render Paris from English Wikipedia with working page previews.

wfLoadExtension( 'MobileFrontendContentProvider' );
wfLoadExtension( 'Popups' );
$wgThumbnailStepsRatio = 1;
$wgThumbnailSteps = [ 20, 40, 60, 120, 250, 330, 500, 960, 1280, 1920, 3840 ];
$wgPopupsRestGatewayEndpoint = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
$wgPopupsGateway = 'restbaseHTML';

Примечания