Help:TemplateStyles/ru

From mediawiki.org
This page is a translated version of the page Help:TemplateStyles and the translation is 28% complete.
Outdated translations are marked like this.
PD Примечание: Редактируя эту страницу, вы соглашаетесь на передачу своего вклада по лицензии CC0.
Подробнее — в проекте Помощь с общественным достоянием.
PD

Расширение: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 затруднены или невозможны.
  • Styles have to be repeated for each HTML element they apply to, which results in lots of copy-pasting and code that is hard to read and maintain.
  • Style attributes are limited to a subset of CSS. Most importantly, @media rules needed for responsive design do not work so it's impossible to make templates that work well over a wide range of screen sizes. Furthermore, inline styles take precedence over CSS stylesheets so user-, skin- or device-specific customizations become more difficult.

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

  • Редактирование ограничено администраторами, что является серьёзным препятствием для участия.
  • 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.
  • 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 позволяет редакторам связывать правила стилей с определёнными страницами, обеспечивает полную мощь таблиц стилей CSS при фильтрации опасных конструкций и работает с инструментами предварительного просмотра/отладки (такими как Расширение:TemplateSandbox ), как и ожидалось.

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).

Это безопасно?

Да! TemplateStyles включает в себя полноценный синтаксический анализатор CSS, который читает, повторно сериализует и экранирует весь код и удаляет правила CSS, которые не соответствуют его белому списку. Синтаксический анализатор достаточно детализирован, чтобы отклонить внешние ресурсы (например, фоновые изображения), но разрешить локальные. Селекторы CSS переписываются так, что они не могут ссылаться на элементы вне содержимого статьи. (Визуальное изменение областей вне содержимого статьи путём перемещения части статьи, например, посредством абсолютного позиционирования, в настоящее время не предотвращается. Это не является изменением статус-кво, поскольку такая вещь уже была возможна с wikitext и встроенными стилями.)

Какие правила CSS распознаются?

В настоящее время TemplateStyles принимает большинство свойств CSS3, поддерживаемых одним или несколькими основными браузерами (по состоянию на начало 2017 года). Помимо простых правил, также поддерживаются at-правила @media, @page, @supports, @keyframe and @font-face/@font-feature-values (по соображениям безопасности @font-face ограничено шрифтами, имя которых начинается с TemplateStyles). For a comprehensive list of allowed properties, see the "$props" parts of the StylePropertySanitizer code from css-sanitizer .

Нестандартные свойства (включая префиксы поставщиков) в настоящее время не поддерживаются. 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; }

How do I use styles in MediaWiki messages?

To prevent a malicious user from messing with the parts of the document outside the main content area, all CSS rules automatically get prefixed by the mw-parser-output CSS class. If you use a TemplateStyles-based template outside of the content area (e.g. in the sitenotice ), you need to provide that class yourself, by wrapping the template in something like <div class="mw-parser-output">...</div>.

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.)

How can Lua modules interact with styles?

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;

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 "Ссылки сюда" option, see what stylesheets are used on a page under "Сведения о странице" (and possibly on the edit screen, depending on what editor you use), and see what recent changes might be affecting a page using "Связанные правки".

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), consisting of Brad Jorsch (developer), Bryan Davis (manager) and Gergő Tisza (developer) at the time. People and responsibilities have since moved around; see the maintainers page for current ownership.

Where do I report errors / ask for features?

Please file tasks under the TemplateStyles component in Phabricator.

Где я могу увидеть это в действии?

Вы можете посмотреть на некоторые кураторские примеры.

Эта функция включена на всех сайтах Викимедиа.

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