Help:TemplateStyles/ru

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Help:TemplateStyles and the translation is 21% complete.
Other languages:
Deutsch • ‎English • ‎français • ‎română • ‎русский • ‎سنڌي • ‎中文 • ‎日本語 • ‎한국어

TemplateStyles - это инструмент, позволяющий создавать сложные стили для шаблонов без прав администратора.

Как это работает?

Редакторы могут добавить <templatestyles src="[some page]" /> на страницу, и содержимое [some page] будет проанализировано как CSS, обработано и загружено на страницы, где используется тег <templatestyles>(напрямую или в используемом шаблоне на странице).

[some page] должен иметь sanitized-css (Sanitized CSS) контент модель, которая будет использована по умолчанию на "подстраницах" относящихся к пространству имен данного Шаблона и иметь расширение в конце .css. Это рекомендованный к использованию паттерн, который выражен в хранении стилей Template:Foo на подстранице Template:Foo/styles.css.

Если у [some page] отсутствует префикс пространства имен, по умолчанию используется пространство имен Template:(Шаблон:). Так, например, <templatestyles src = "Foo/styles.css" /> загрузит Template:Foo/styles.css.

Тег <templatestyles> должен быть помещен перед стилем, который оформлен, например, в верхней части шаблона, чтобы избежать потенциально нежелательного содержимого, если страница частично отображается при загрузке.

Какие проблемы это решает?

Традиционно есть два способа стилизовать шаблоны (или любой другой контент): используя встроенные стили (то есть, используя HTML-код и добавляя к нему такие атрибуты, как style= "margin: 10px") или используя определенные специальные системные сообщения, такие как MediaWiki:Common.css. Ни один из этих подходов не работает очень хорошо.

Для встроенного стиля:

  • Нет разделения контента и презентации. В случаях, когда содержимое не приходит из шаблона (например, таблицы в статьях), это приведет к появлению статьи в викитексте, которая непонятна большинству редакторов.
  • Поскольку стили смешаны с викитекстом, подсветка синтаксиса и другие формы поддержки редактирования CSS трудны или невозможны.
  • Стили должны повторяться для каждого элемента HTML, к которому они применяются, что приводит к большому количеству вставки копий и кода, который трудно читать и поддерживать.
  • Атрибуты стиля ограничены подмножеством CSS. Самое главное, правила @media, необходимые для отзывчивый дизайн, не работают, поэтому невозможно создать шаблоны, которые хорошо работают на широком диапазоне размеров экрана. Кроме того, встроенные стили имеют приоритет над таблицами стилей CSS, поэтому настройки для пользователя, скина или устройства становятся более сложными.

Для системных MediaWiki:*.css страниц:

  • Editing is limited to administrators, which is a major barrier to participation.
  • Editing restrictions cannot be lifted as there is no way to limit what CSS rules can be used, and some of them could be abused to track readers' IP addresses or even execute scripts in some older browsers.
  • Changes are impossible to test without saving first (задача T112474).
  • All stylesheets must be loaded on all pages (whether they actually use the page or not), which wastes bandwidth and makes debugging style rules harder.

TemplateStyles allows editors to associate style rules to specific pages, provides the full power of CSS stylesheets while filtering dangerous constructs, and works with preview/debug tools (such as TemplateSandbox) as expected.

Lowering the access and maintainability barrier will hopefully result in more innovation in the way templates are visually designed, less maintenance overhead, and better adaptability to screen options (especially mobile devices which by now constitute half of Wikipedia pageviews).

Is it safe?

Yes! TemplateStyles includes a full-fledged CSS parser that reads, re-serializes and escapes all code and removes CSS rules which do not match its whitelist. The parser is sufficiently fine-grained to reject remote resources (such as background images) but allow local ones. CSS selectors are rewritten so that they cannot refer to elements outside article content. (Visually modifying areas outside article content by displacing parts of the article, e.g. via absolute positioning, is not prevented at this time. This is no change from the status quo, as such a thing was already possible with wikitext and inline styles.)

What CSS rules are recognized?

Currently, TemplateStyles accepts most CSS3 properties supported by one or more major browser (as of early 2017). Beyond simple rules, @media, @page, @supports, @keyframe and @font-face/@font-feature-values at-rules are also supported (with font-face restricted to fonts whose name starts with TemplateStyles, for security reasons). For a comprehensive list of allowed properties, see the "$props" parts of the StylePropertySanitizer code from css-sanitizer .

Non-standard properties (including vendor prefixes) are not currently supported. See T162379 for plans.

How can I target mobile/desktop resolutions?

Media queries allow you to target elements at mobile resolution and desktop resolution. Some advise making your styles mobile friendly by default and wrapping desktop styles within the media query. Note, MediaWiki has standardised on 720px and 1000px breakpoints to represent tablet and desktop.

How can I target specific skins?

MediaWiki provides various classes on the html and body elements, including one that indicates which skin is in use. These can be targeted by including a simple selector for the html or body element including the needed classes, followed by a space (or in CSS terms, the descendant combinator).

Generally, this technique should be used for design consistency, rather than targeting mobile and desktop as all skins can be used in both mobile and desktop resolutions. See also #How can I target mobile/desktop resolutions?.

/* Elements with class 'foo' will have red text in all skins */
.foo { color: red; }

/* Override that to green for Vector only */
body.skin-vector .foo { color: green; }

/* Add a red border if the user doesn't have JavaScript enabled */
html.client-nojs .foo { border: 1px solid red; }

/* Make that border green in Vector */
html.client-nojs body.skin-vector .foo { border-color: green; }
/* This does not work! The 'body' element must be specified. */
.skin-vector .foo { background: orange; }

/* These do not work! The descendant combinator must be used */
body.skin-vector > .foo { background: orange; }
body.skin-vector ~ .foo { background: orange; }
html.client-nojs > body.skin-vector .foo { background: orange; }

In which order do CSS styles override?

Which CSS rule takes effect is controlled by specificity (roughly, the complexity of the selector - e.g. div.foo { margin: 10px } is more specific than .foo { margin: 5px }). In case of equal specificity, CSS styles that come later in the document override earlier styles.

MediaWiki:Commons.css, other site scripts, user scripts and gadgets are loaded in the <head> section of the page. TemplateStyles stylesheets are loaded in the <body>, so they override site/user script and gadget rules with equal specificity, and in the case of two TemplateStyles rules, the second overrides the first. (Note though that TemplateStyles rules are deduplicated: if the same stylesheet is referenced multiple times on the page, it is only inserted the first time. Note also that "later" has to do with document position, not load order. Gadgets add their CSS after the page has fully loaded, by manipulating the page with JavaScript; some add it on-demand when the user does some action such as clicking a button. Nevertheless, they add it to the head, so equally-specific CSS rules in the body get precedence over it.)

What anti-abuse features are provided?

The design choice to store CSS in separate pages was made in part to make integration with the standard anti-abuse toolset easy. TemplateStyles CSS pages have their own content model (sanitized-css) so changes to them can be tracked or controlled with AbuseFilter, using the new_content_model variable.

CSS inclusion is tracked the same way as template transclusion, so you can see where a stylesheet is used via the "What links here" option, see what stylesheets are used on a page under "Page information" (and possibly on the edit screen, depending on what editor you use), and see what recent changes might be affecting a page using "Related changes".

TemplateStyles also leaves identifying information in the HTML code; to find out where a specific rule comes from, look at the page source, and the enclosing <style> tag will have an attribute like data-mw-deduplicate="TemplateStyles:r123456", where 123456 is the revision ID of the stylesheet (viewable with Special:Diff, for example).

How were the decisions around TemplateStyles made?

The idea of including CSS with templates was proposed and accepted in a request for comments. Technical details were pinned down in a second RfC and workflow details in a user consultation.

Who is working on TemplateStyles?

TemplateStyles was originally a project of the Wikimedia Reading Infrastructure team (preceded by exploratory work Coren did as a volunteer), then people moved around. It is now maintained by an ad hoc WMF team consisting of Brad Jorsch (developer), Chris Koerner (community liaison), Dan Garry (product manager), Gergő Tisza (developer) and Grace Gellerman (project manager).

Where do I report errors / ask for features?

Please file tasks under the TemplateStyles component in Phabricator.

Where can I see it in action?

You can look at some curated examples.

The feature is enabled on all Wikimedia sites.

Calling from a Lua module

TemplateStyles can be called from a Lua module using frame:extensionTag.

Example code is the following:

local p = {};

function p.templateStyle( frame, src )
   return frame:extensionTag( 'templatestyles', '', { src = src } );
end

return p;

Смотрите также