3 * ResourceLoader module for generated and embedded images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Trevor Parscal
25 * ResourceLoader module for generated and embedded images.
29 class ResourceLoaderImageModule
extends ResourceLoaderModule
{
31 protected $definition = null;
34 * Local base path, see __construct()
37 protected $localBasePath = '';
39 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
41 protected $images = [];
42 protected $variants = [];
43 protected $prefix = null;
44 protected $selectorWithoutVariant = '.{prefix}-{name}';
45 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
46 protected $targets = [ 'desktop', 'mobile' ];
49 * Constructs a new module from an options array.
51 * @param array $options List of options; if not given or empty, an empty module will be
53 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
56 * Below is a description for the $options array:
57 * @par Construction options:
60 * // Base path to prepend to all local paths in $options. Defaults to $IP
61 * 'localBasePath' => [base path],
62 * // Path to JSON file that contains any of the settings below
63 * 'data' => [file path string]
64 * // CSS class prefix to use in all style rules
65 * 'prefix' => [CSS class prefix],
66 * // Alternatively: Format of CSS selector to use in all style rules
67 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
68 * // Alternatively: When using variants
69 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
70 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
71 * // List of variants that may be used for the image files
73 * // This level of nesting can be omitted if you use the same images for every skin
74 * [skin name (or 'default')] => [
76 * 'color' => [color string, e.g. '#ffff00'],
77 * 'global' => [boolean, if true, this variant is available
78 * for all images of this type],
84 * // List of image files and their options
86 * // This level of nesting can be omitted if you use the same images for every skin
87 * [skin name (or 'default')] => [
89 * 'file' => [file path string or array whose values are file path strings
90 * and whose keys are 'default', 'ltr', 'rtl', a single
91 * language code like 'en', or a list of language codes like
93 * 'variants' => [array of variant name strings, variants
94 * available for this image],
102 * @throws InvalidArgumentException
104 public function __construct( $options = [], $localBasePath = null ) {
105 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
107 $this->definition
= $options;
111 * Parse definition and external JSON data, if referenced.
113 protected function loadFromDefinition() {
114 if ( $this->definition
=== null ) {
118 $options = $this->definition
;
119 $this->definition
= null;
121 if ( isset( $options['data'] ) ) {
122 $dataPath = $this->localBasePath
. '/' . $options['data'];
123 $data = json_decode( file_get_contents( $dataPath ), true );
124 $options = array_merge( $data, $options );
127 // Accepted combinations:
130 // * selectorWithoutVariant + selectorWithVariant
131 // * prefix + selector
132 // * prefix + selectorWithoutVariant + selectorWithVariant
134 $prefix = isset( $options['prefix'] ) && $options['prefix'];
135 $selector = isset( $options['selector'] ) && $options['selector'];
136 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
137 && $options['selectorWithoutVariant'];
138 $selectorWithVariant = isset( $options['selectorWithVariant'] )
139 && $options['selectorWithVariant'];
141 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
142 throw new InvalidArgumentException(
143 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
146 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
147 throw new InvalidArgumentException(
148 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
151 if ( $selector && $selectorWithVariant ) {
152 throw new InvalidArgumentException(
153 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
156 if ( !$prefix && !$selector && !$selectorWithVariant ) {
157 throw new InvalidArgumentException(
158 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
162 foreach ( $options as $member => $option ) {
166 if ( !is_array( $option ) ) {
167 throw new InvalidArgumentException(
168 "Invalid list error. '$option' given, array expected."
171 if ( !isset( $option['default'] ) ) {
172 // Backwards compatibility
173 $option = [ 'default' => $option ];
175 foreach ( $option as $skin => $data ) {
176 if ( !is_array( $option ) ) {
177 throw new InvalidArgumentException(
178 "Invalid list error. '$option' given, array expected."
182 $this->{$member} = $option;
186 case 'selectorWithoutVariant':
187 case 'selectorWithVariant':
188 $this->{$member} = (string)$option;
192 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
198 * Get CSS class prefix used by this module.
201 public function getPrefix() {
202 $this->loadFromDefinition();
203 return $this->prefix
;
207 * Get CSS selector templates used by this module.
210 public function getSelectors() {
211 $this->loadFromDefinition();
213 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
214 'selectorWithVariant' => $this->selectorWithVariant
,
219 * Get a ResourceLoaderImage object for given image.
220 * @param string $name Image name
221 * @param ResourceLoaderContext $context
222 * @return ResourceLoaderImage|null
224 public function getImage( $name, ResourceLoaderContext
$context ) {
225 $this->loadFromDefinition();
226 $images = $this->getImages( $context );
227 return $images[$name] ??
null;
231 * Get ResourceLoaderImage objects for all images.
232 * @param ResourceLoaderContext $context
233 * @return ResourceLoaderImage[] Array keyed by image name
235 public function getImages( ResourceLoaderContext
$context ) {
236 $skin = $context->getSkin();
237 if ( !isset( $this->imageObjects
) ) {
238 $this->loadFromDefinition();
239 $this->imageObjects
= [];
241 if ( !isset( $this->imageObjects
[$skin] ) ) {
242 $this->imageObjects
[$skin] = [];
243 if ( !isset( $this->images
[$skin] ) ) {
244 $this->images
[$skin] = $this->images
['default'] ??
[];
246 foreach ( $this->images
[$skin] as $name => $options ) {
247 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
249 $allowedVariants = array_merge(
250 ( is_array( $options ) && isset( $options['variants'] ) ) ?
$options['variants'] : [],
251 $this->getGlobalVariants( $context )
253 if ( isset( $this->variants
[$skin] ) ) {
254 $variantConfig = array_intersect_key(
255 $this->variants
[$skin],
256 array_fill_keys( $allowedVariants, true )
262 $image = new ResourceLoaderImage(
266 $this->localBasePath
,
269 $this->imageObjects
[$skin][$image->getName()] = $image;
273 return $this->imageObjects
[$skin];
277 * Get list of variants in this module that are 'global', i.e., available
278 * for every image regardless of image options.
279 * @param ResourceLoaderContext $context
282 public function getGlobalVariants( ResourceLoaderContext
$context ) {
283 $skin = $context->getSkin();
284 if ( !isset( $this->globalVariants
) ) {
285 $this->loadFromDefinition();
286 $this->globalVariants
= [];
288 if ( !isset( $this->globalVariants
[$skin] ) ) {
289 $this->globalVariants
[$skin] = [];
290 if ( !isset( $this->variants
[$skin] ) ) {
291 $this->variants
[$skin] = $this->variants
['default'] ??
[];
293 foreach ( $this->variants
[$skin] as $name => $config ) {
294 if ( isset( $config['global'] ) && $config['global'] ) {
295 $this->globalVariants
[$skin][] = $name;
300 return $this->globalVariants
[$skin];
304 * @param ResourceLoaderContext $context
307 public function getStyles( ResourceLoaderContext
$context ) {
308 $this->loadFromDefinition();
312 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
313 $selectors = $this->getSelectors();
315 foreach ( $this->getImages( $context ) as $name => $image ) {
316 $declarations = $this->getStyleDeclarations( $context, $image, $script );
318 $selectors['selectorWithoutVariant'],
320 '{prefix}' => $this->getPrefix(),
325 $rules[] = "$selector {\n\t$declarations\n}";
327 foreach ( $image->getVariants() as $variant ) {
328 $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
330 $selectors['selectorWithVariant'],
332 '{prefix}' => $this->getPrefix(),
334 '{variant}' => $variant,
337 $rules[] = "$selector {\n\t$declarations\n}";
341 $style = implode( "\n", $rules );
342 return [ 'all' => $style ];
346 * @param ResourceLoaderContext $context
347 * @param ResourceLoaderImage $image Image to get the style for
348 * @param string $script URL to load.php
349 * @param string|null $variant Variant to get the style for
352 private function getStyleDeclarations(
353 ResourceLoaderContext
$context,
354 ResourceLoaderImage
$image,
358 $imageDataUri = $image->getDataUri( $context, $variant, 'original' );
359 $primaryUrl = $imageDataUri ?
: $image->getUrl( $context, $script, $variant, 'original' );
360 $declarations = $this->getCssDeclarations(
362 $image->getUrl( $context, $script, $variant, 'rasterized' )
364 return implode( "\n\t", $declarations );
368 * SVG support using a transparent gradient to guarantee cross-browser
369 * compatibility (browsers able to understand gradient syntax support also SVG).
370 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
372 * Keep synchronized with the .background-image-svg LESS mixin in
373 * /resources/src/mediawiki.less/mediawiki.mixins.less.
375 * @param string $primary Primary URI
376 * @param string $fallback Fallback URI
377 * @return string[] CSS declarations to use given URIs as background-image
379 protected function getCssDeclarations( $primary, $fallback ) {
380 $primaryUrl = CSSMin
::buildUrlValue( $primary );
381 $fallbackUrl = CSSMin
::buildUrlValue( $fallback );
383 "background-image: $fallbackUrl;",
384 "background-image: linear-gradient(transparent, transparent), $primaryUrl;",
391 public function supportsURLLoading() {
396 * Get the definition summary for this module.
398 * @param ResourceLoaderContext $context
401 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
402 $this->loadFromDefinition();
403 $summary = parent
::getDefinitionSummary( $context );
411 'selectorWithoutVariant',
412 'selectorWithVariant',
414 $options[$member] = $this->{$member};
418 'options' => $options,
419 'fileHashes' => $this->getFileHashes( $context ),
425 * Helper method for getDefinitionSummary.
426 * @param ResourceLoaderContext $context
429 protected function getFileHashes( ResourceLoaderContext
$context ) {
430 $this->loadFromDefinition();
432 foreach ( $this->getImages( $context ) as $name => $image ) {
433 $files[] = $image->getPath( $context );
435 $files = array_values( array_unique( $files ) );
436 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
440 * Extract a local base path from module definition information.
442 * @param array $options Module definition
443 * @param string $localBasePath Path to use if not provided in module definition. Defaults
445 * @return string Local base path
447 public static function extractLocalBasePath( $options, $localBasePath = null ) {
450 if ( $localBasePath === null ) {
451 $localBasePath = $IP;
454 if ( array_key_exists( 'localBasePath', $options ) ) {
455 $localBasePath = (string)$options['localBasePath'];
458 return $localBasePath;
464 public function getType() {
465 return self
::LOAD_STYLES
;