MediaWiki  master
ResourceLoaderSkinModule.php
Go to the documentation of this file.
1 <?php
20 use Wikimedia\Minify\CSSMin;
21 
32  public $targets = [ 'desktop', 'mobile' ];
33 
116  private const FEATURE_FILES = [
117  'normalize' => [
118  'all' => [ 'resources/src/mediawiki.skinning/normalize.less' ],
119  ],
120  'logo' => [
121  // Applies the logo and ensures it downloads prior to printing.
122  'all' => [ 'resources/src/mediawiki.skinning/logo.less' ],
123  // Reserves whitespace for the logo in a pseudo element.
124  'print' => [ 'resources/src/mediawiki.skinning/logo-print.less' ],
125  ],
126  'content-media' => [
127  'screen' => [ 'resources/src/mediawiki.skinning/content.thumbnails.less' ],
128  'print' => [ 'resources/src/mediawiki.skinning/content.thumbnails-print.less' ],
129  ],
130  'content-links' => [
131  'screen' => [ 'resources/src/mediawiki.skinning/content.links.less' ]
132  ],
133  'content-links-external' => [
134  'screen' => [ 'resources/src/mediawiki.skinning/content.externallinks.less' ]
135  ],
136  'content-body' => [
137  'screen' => [ 'resources/src/mediawiki.skinning/content.body.less' ],
138  'print' => [ 'resources/src/mediawiki.skinning/content.body-print.less' ],
139  ],
140  'content-tables' => [
141  'screen' => [ 'resources/src/mediawiki.skinning/content.tables.less' ],
142  'print' => [ 'resources/src/mediawiki.skinning/content.tables-print.less' ]
143  ],
144  'interface' => [
145  'screen' => [ 'resources/src/mediawiki.skinning/interface.less' ],
146  'print' => [ 'resources/src/mediawiki.skinning/interface-print.less' ],
147  ],
148  'interface-category' => [
149  'screen' => [ 'resources/src/mediawiki.skinning/interface.category.less' ],
150  'print' => [ 'resources/src/mediawiki.skinning/interface.category-print.less' ],
151  ],
152  'interface-message-box' => [
153  'all' => [ 'resources/src/mediawiki.skinning/messageBoxes.less' ],
154  ],
155  'elements' => [
156  'screen' => [ 'resources/src/mediawiki.skinning/elements.less' ],
157  'print' => [ 'resources/src/mediawiki.skinning/elements-print.less' ],
158  ],
159  'legacy' => [
160  'all' => [ 'resources/src/mediawiki.skinning/messageBoxes.less' ],
161  'print' => [ 'resources/src/mediawiki.skinning/commonPrint.less' ],
162  'screen' => [ 'resources/src/mediawiki.skinning/legacy.less' ],
163  ],
164  'i18n-ordered-lists' => [
165  'screen' => [ 'resources/src/mediawiki.skinning/i18n-ordered-lists.less' ],
166  ],
167  'i18n-all-lists-margins' => [
168  'screen' => [ 'resources/src/mediawiki.skinning/i18n-all-lists-margins.less' ],
169  ],
170  'i18n-headings' => [
171  'screen' => [ 'resources/src/mediawiki.skinning/i18n-headings.less' ],
172  ],
173  'toc' => [
174  'all' => [ 'resources/src/mediawiki.skinning/toc/common.css' ],
175  'screen' => [ 'resources/src/mediawiki.skinning/toc/screen.less' ],
176  'print' => [ 'resources/src/mediawiki.skinning/toc/print.css' ],
177  ],
178  ];
179 
181  private $features;
182 
190  private const DEFAULT_FEATURES_SPECIFIED = [
191  'content-body' => true,
192  'toc' => true,
193  ];
194 
203  private const DEFAULT_FEATURES_ABSENT = [
204  'logo',
205  'legacy',
206  ];
207 
208  private const LESS_MESSAGES = [
209  // `toc` feature, used in screen.less
210  'hidetoc',
211  'showtoc',
212  ];
213 
234  public function __construct(
235  array $options = [],
236  $localBasePath = null,
237  $remoteBasePath = null
238  ) {
239  $features = $options['features'] ?? self::DEFAULT_FEATURES_ABSENT;
240  $listMode = array_keys( $features ) === range( 0, count( $features ) - 1 );
241 
242  $messages = '';
243  // NOTE: Compatibility is only applied when features are provided
244  // in map-form. The list-form does not currently get these.
245  $features = $listMode ? self::applyFeaturesCompatibility( array_fill_keys( $features, true ), $messages ) :
247 
248  foreach ( $features as $key => $enabled ) {
249  if ( !isset( self::FEATURE_FILES[$key] ) ) {
250  throw new InvalidArgumentException( "Feature '$key' is not recognised" );
251  }
252  }
253 
254  $this->features = $listMode
255  ? array_keys( array_filter( $features ) )
256  : array_keys( array_filter( $features + self::DEFAULT_FEATURES_SPECIFIED ) );
257 
258  // Only the `toc` feature makes use of interface messages.
259  // For skins not using the `toc` feature, make sure LocalisationCache
260  // remains untouched (T270027).
261  if ( in_array( 'toc', $this->features ) ) {
262  $options['lessMessages'] = array_merge(
263  $options['lessMessages'] ?? [],
264  self::LESS_MESSAGES
265  );
266  }
267 
268  if ( $messages !== '' ) {
269  $messages .= 'More information can be found at [[mw:Manual:ResourceLoaderSkinModule]]. ';
270  $options['deprecated'] = $messages;
271  }
272  parent::__construct( $options, $localBasePath, $remoteBasePath );
273  }
274 
281  protected static function applyFeaturesCompatibility( array $features, &$messages = '' ): array {
282  // The `content` feature is mapped to `content-media`.
283  if ( isset( $features[ 'content' ] ) ) {
284  $features[ 'content-media' ] = $features[ 'content' ];
285  unset( $features[ 'content' ] );
286  $messages .= '[1.37] The use of the `content` feature with ResourceLoaderSkinModule'
287  . ' is deprecated. Use `content-media` instead. ';
288  }
289 
290  // The `content-thumbnails` feature is mapped to `content-media`.
291  if ( isset( $features[ 'content-thumbnails' ] ) ) {
292  $features[ 'content-media' ] = $features[ 'content-thumbnails' ];
293  $messages .= '[1.37] The use of the `content-thumbnails` feature with ResourceLoaderSkinModule'
294  . ' is deprecated. Use `content-media` instead. ';
295  unset( $features[ 'content-thumbnails' ] );
296  }
297 
298  // If `content-links` feature is set but no preference for `content-links-external` is set
299  if ( isset( $features[ 'content-links' ] ) && !isset( $features[ 'content-links-external' ] ) ) {
300  // Assume the same true/false preference for both.
301  $features[ 'content-links-external' ] = $features[ 'content-links' ];
302  }
303 
304  // The legacy feature is deprecated (T89981).
305  if ( isset( $features['legacy'] ) && $features['legacy'] ) {
306  $messages .= '[1.37] The use of the `legacy` feature with ResourceLoaderSkinModule is deprecated'
307  . '(T89981). ';
308  }
309 
310  // The `content-links` feature was split out from `elements`.
311  // Make sure skins asking for `elements` also get these by default.
312  if ( isset( $features[ 'element' ] ) && !isset( $features[ 'content-links' ] ) ) {
313  $features[ 'content-links' ] = $features[ 'element' ];
314  }
315 
316  // `content-parser-output` was renamed to `content-body`.
317  // No need to go through deprecation process here since content-parser-output added and removed in 1.36.
318  // Remove this check when no matches for
319  // https://codesearch.wmcloud.org/search/?q=content-parser-output&i=nope&files=&excludeFiles=&repos=
320  if ( isset( $features[ 'content-parser-output' ] ) ) {
321  $features[ 'content-body' ] = $features[ 'content-parser-output' ];
322  unset( $features[ 'content-parser-output' ] );
323  }
324 
325  return $features;
326  }
327 
334  public function getStyleFiles( ResourceLoaderContext $context ) {
335  $styles = parent::getStyleFiles( $context );
336 
337  // Bypass the current module paths so that these files are served from core,
338  // instead of the individual skin's module directory.
339  list( $defaultLocalBasePath, $defaultRemoteBasePath ) =
341  [],
342  null,
343  $this->getConfig()->get( 'ResourceBasePath' )
344  );
345 
346  $featureFilePaths = [];
347 
348  foreach ( self::FEATURE_FILES as $feature => $featureFiles ) {
349  if ( in_array( $feature, $this->features ) ) {
350  foreach ( $featureFiles as $mediaType => $files ) {
351  foreach ( $files as $filepath ) {
352  $featureFilePaths[$mediaType][] = new ResourceLoaderFilePath(
353  $filepath,
354  $defaultLocalBasePath,
355  $defaultRemoteBasePath
356  );
357  }
358  }
359  if ( $feature === 'content-media' && (
360  !$this->getConfig()->get( 'ParserEnableLegacyMediaDOM' ) ||
361  $this->getConfig()->get( 'UseContentMediaStyles' )
362  ) ) {
363  $featureFilePaths['screen'][] = new ResourceLoaderFilePath(
364  'resources/src/mediawiki.skinning/content.media.less',
365  $defaultLocalBasePath,
366  $defaultRemoteBasePath
367  );
368  }
369  }
370  }
371 
372  // Styles defines in options are added to the $featureFilePaths to ensure
373  // that $featureFilePaths styles precede module defined ones.
374  // This is particularly important given the `normalize` styles need to be the first
375  // outputted (see T269618).
376  foreach ( $styles as $mediaType => $paths ) {
377  $featureFilePaths[$mediaType] = array_merge( $featureFilePaths[$mediaType] ?? [], $paths );
378  }
379 
380  return $featureFilePaths;
381  }
382 
387  public function getStyles( ResourceLoaderContext $context ) {
388  $logo = $this->getLogoData( $this->getConfig() );
389  $styles = parent::getStyles( $context );
390  $this->normalizeStyles( $styles );
391 
392  $isLogoFeatureEnabled = in_array( 'logo', $this->features );
393  if ( $isLogoFeatureEnabled ) {
394  $default = !is_array( $logo ) ? $logo : $logo['1x'];
395  $styles['all'][] = '.mw-wiki-logo { background-image: ' .
396  CSSMin::buildUrlValue( $default ) .
397  '; }';
398 
399  if ( is_array( $logo ) ) {
400  if ( isset( $logo['svg'] ) ) {
401  $styles['all'][] = '.mw-wiki-logo { ' .
402  'background-image: -webkit-linear-gradient(transparent, transparent), ' .
403  CSSMin::buildUrlValue( $logo['svg'] ) . '; ' .
404  'background-image: linear-gradient(transparent, transparent), ' .
405  CSSMin::buildUrlValue( $logo['svg'] ) . ';' .
406  'background-size: 135px auto; }';
407  } else {
408  if ( isset( $logo['1.5x'] ) ) {
409  $styles[
410  '(-webkit-min-device-pixel-ratio: 1.5), ' .
411  '(min-resolution: 1.5dppx), ' .
412  '(min-resolution: 144dpi)'
413  ][] = '.mw-wiki-logo { background-image: ' .
414  CSSMin::buildUrlValue( $logo['1.5x'] ) . ';' .
415  'background-size: 135px auto; }';
416  }
417  if ( isset( $logo['2x'] ) ) {
418  $styles[
419  '(-webkit-min-device-pixel-ratio: 2), ' .
420  '(min-resolution: 2dppx), ' .
421  '(min-resolution: 192dpi)'
422  ][] = '.mw-wiki-logo { background-image: ' .
423  CSSMin::buildUrlValue( $logo['2x'] ) . ';' .
424  'background-size: 135px auto; }';
425  }
426  }
427  }
428  }
429 
430  return $styles;
431  }
432 
437  public function getPreloadLinks( ResourceLoaderContext $context ) {
438  return $this->getLogoPreloadlinks();
439  }
440 
445  private function getLogoPreloadlinks(): array {
446  if ( !in_array( 'logo', $this->features ) ) {
447  return [];
448  }
449 
450  $logo = $this->getLogoData( $this->getConfig() );
451 
452  if ( !is_array( $logo ) ) {
453  // No media queries required if we only have one variant
454  return [ $logo => [ 'as' => 'image' ] ];
455  }
456 
457  if ( isset( $logo['svg'] ) ) {
458  // No media queries required if we only have a 1x and svg variant
459  // because all preload-capable browsers support SVGs
460  return [ $logo['svg'] => [ 'as' => 'image' ] ];
461  }
462 
463  $logosPerDppx = [];
464  foreach ( $logo as $dppx => $src ) {
465  // Keys are in this format: "1.5x"
466  $dppx = substr( $dppx, 0, -1 );
467  $logosPerDppx[$dppx] = $src;
468  }
469 
470  // Because PHP can't have floats as array keys
471  uksort( $logosPerDppx, static function ( $a, $b ) {
472  $a = floatval( $a );
473  $b = floatval( $b );
474  // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
475  return $a <=> $b;
476  } );
477 
478  $logos = [];
479  foreach ( $logosPerDppx as $dppx => $src ) {
480  $logos[] = [
481  'dppx' => $dppx,
482  'src' => $src
483  ];
484  }
485 
486  $logosCount = count( $logos );
487  $preloadLinks = [];
488  // Logic must match ResourceLoaderSkinModule:
489  // - 1x applies to resolution < 1.5dppx
490  // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
491  // - 2x applies to resolution >= 2dppx
492  // Note that min-resolution and max-resolution are both inclusive.
493  for ( $i = 0; $i < $logosCount; $i++ ) {
494  if ( $i === 0 ) {
495  // Smallest dppx
496  // min-resolution is ">=" (larger than or equal to)
497  // "not min-resolution" is essentially "<"
498  $media_query = 'not all and (min-resolution: ' . $logos[1]['dppx'] . 'dppx)';
499  } elseif ( $i !== $logosCount - 1 ) {
500  // In between
501  // Media query expressions can only apply "not" to the entire expression
502  // (e.g. can't express ">= 1.5 and not >= 2).
503  // Workaround: Use <= 1.9999 in place of < 2.
504  $upper_bound = floatval( $logos[$i + 1]['dppx'] ) - 0.000001;
505  $media_query = '(min-resolution: ' . $logos[$i]['dppx'] .
506  'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
507  } else {
508  // Largest dppx
509  $media_query = '(min-resolution: ' . $logos[$i]['dppx'] . 'dppx)';
510  }
511 
512  $preloadLinks[$logos[$i]['src']] = [
513  'as' => 'image',
514  'media' => $media_query
515  ];
516  }
517 
518  return $preloadLinks;
519  }
520 
529  private function normalizeStyles( array &$styles ): void {
530  foreach ( $styles as $key => $val ) {
531  if ( !is_array( $val ) ) {
532  $styles[$key] = [ $val ];
533  }
534  }
535  }
536 
543  private static function getRelativeSizedLogo( array $logoElement ) {
544  $width = $logoElement['width'];
545  $height = $logoElement['height'];
546  $widthRelative = $width / 16;
547  $heightRelative = $height / 16;
548  // Allow skins to scale the wordmark with browser font size (T207789)
549  $logoElement['style'] = 'width: ' . $widthRelative . 'em; height: ' . $heightRelative . 'em;';
550  return $logoElement;
551  }
552 
567  public static function getAvailableLogos( $conf ): array {
568  $logos = $conf->get( 'Logos' );
569  if ( $logos === false ) {
570  // no logos were defined... this will either
571  // 1. Load from wgLogo and wgLogoHD
572  // 2. Trigger runtime exception if those are not defined.
573  $logos = [];
574  }
575 
576  // If logos['1x'] is not defined, see if we can use wgLogo
577  if ( !isset( $logos[ '1x' ] ) ) {
578  $logo = $conf->get( 'Logo' );
579  if ( $logo ) {
580  $logos['1x'] = $logo;
581  }
582  }
583 
584  try {
585  $logoHD = $conf->get( 'LogoHD' );
586  // make sure not false
587  if ( $logoHD ) {
588  // wfDeprecated( __METHOD__ . ' with $wgLogoHD set instead of $wgLogos', '1.35', false, 1 );
589  $logos += $logoHD;
590  }
591  } catch ( ConfigException $e ) {
592  // no backwards compatibility changes needed.
593  }
594 
595  // check the configuration is valid
596  if ( !isset( $logos['1x'] ) ) {
597  throw new RuntimeException( "The key `1x` is required for wgLogos or wgLogo must be defined." );
598  }
599 
600  // @todo: Note the beta cluster and other wikis may be using
601  // unsupported configuration where these values are set to false.
602  // The boolean check can be removed when this has been addressed.
603  if ( isset( $logos['wordmark'] ) && $logos['wordmark'] ) {
604  // Allow skins to scale the wordmark with browser font size (T207789)
605  $logos['wordmark'] = self::getRelativeSizedLogo( $logos['wordmark'] );
606  }
607 
608  // @todo: Note the beta cluster and other wikis may be using
609  // unsupported configuration where these values are set to false.
610  // The boolean check can be removed when this has been addressed.
611  if ( isset( $logos['tagline'] ) && $logos['tagline'] ) {
612  $logos['tagline'] = self::getRelativeSizedLogo( $logos['tagline'] );
613  }
614  // return the modified logos!
615  return $logos;
616  }
617 
626  protected function getLogoData( Config $conf ) {
627  $logoHD = self::getAvailableLogos( $conf );
628  $logo = $logoHD['1x'];
629 
630  $logo1Url = OutputPage::transformResourcePath( $conf, $logo );
631 
632  $logoUrls = [
633  '1x' => $logo1Url,
634  ];
635 
636  if ( isset( $logoHD['svg'] ) ) {
637  $logoUrls['svg'] = OutputPage::transformResourcePath(
638  $conf,
639  $logoHD['svg']
640  );
641  } elseif ( isset( $logoHD['1.5x'] ) || isset( $logoHD['2x'] ) ) {
642  // Only 1.5x and 2x are supported
643  if ( isset( $logoHD['1.5x'] ) ) {
644  $logoUrls['1.5x'] = OutputPage::transformResourcePath(
645  $conf,
646  $logoHD['1.5x']
647  );
648  }
649  if ( isset( $logoHD['2x'] ) ) {
650  $logoUrls['2x'] = OutputPage::transformResourcePath(
651  $conf,
652  $logoHD['2x']
653  );
654  }
655  } else {
656  // Return a string rather than a one-element array, getLogoPreloadlinks depends on this
657  return $logo1Url;
658  }
659 
660  return $logoUrls;
661  }
662 
667  public function isKnownEmpty( ResourceLoaderContext $context ) {
668  // Regardless of whether the files are specified, we always
669  // provide mw-wiki-logo styles.
670  return false;
671  }
672 
679  protected function getLessVars( ResourceLoaderContext $context ) {
680  $lessVars = parent::getLessVars( $context );
681  $logos = self::getAvailableLogos( $this->getConfig() );
682 
683  if ( isset( $logos['wordmark'] ) ) {
684  $logo = $logos['wordmark'];
685  $lessVars[ 'logo-enabled' ] = true;
686  $lessVars[ 'logo-wordmark-url' ] = CSSMin::buildUrlValue( $logo['src'] );
687  $lessVars[ 'logo-wordmark-width' ] = intval( $logo['width'] );
688  $lessVars[ 'logo-wordmark-height' ] = intval( $logo['height'] );
689  } else {
690  $lessVars[ 'logo-enabled' ] = false;
691  }
692  return $lessVars;
693  }
694 
695  public function getDefinitionSummary( ResourceLoaderContext $context ) {
696  $summary = parent::getDefinitionSummary( $context );
697  $summary[] = [
698  'logos' => self::getAvailableLogos( $this->getConfig() ),
699  ];
700  return $summary;
701  }
702 }
ResourceLoaderLessVarFileModule
Module augmented with context-specific LESS variables.
Definition: ResourceLoaderLessVarFileModule.php:31
ResourceLoaderSkinModule\getPreloadLinks
getPreloadLinks(ResourceLoaderContext $context)
Definition: ResourceLoaderSkinModule.php:437
ResourceLoaderSkinModule\LESS_MESSAGES
const LESS_MESSAGES
Definition: ResourceLoaderSkinModule.php:208
ResourceLoaderContext
Context object that contains information about the state of a specific ResourceLoader web request.
Definition: ResourceLoaderContext.php:34
ResourceLoaderFileModule\$styles
array $styles
List of paths to CSS files to always include.
Definition: ResourceLoaderFileModule.php:93
ResourceLoaderSkinModule\__construct
__construct(array $options=[], $localBasePath=null, $remoteBasePath=null)
Definition: ResourceLoaderSkinModule.php:234
true
return true
Definition: router.php:90
ResourceLoaderSkinModule\normalizeStyles
normalizeStyles(array &$styles)
Ensure all media keys use array values.
Definition: ResourceLoaderSkinModule.php:529
ResourceLoaderFilePath
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path,...
Definition: ResourceLoaderFilePath.php:28
ResourceLoaderSkinModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderSkinModule.php:695
ResourceLoaderSkinModule\$features
string[] $features
Definition: ResourceLoaderSkinModule.php:181
Config
Interface for configuration instances.
Definition: Config.php:30
ResourceLoaderSkinModule\getLessVars
getLessVars(ResourceLoaderContext $context)
Get language-specific LESS variables for this module.
Definition: ResourceLoaderSkinModule.php:679
ConfigException
Exceptions for config failures.
Definition: ConfigException.php:29
ResourceLoaderSkinModule\getRelativeSizedLogo
static getRelativeSizedLogo(array $logoElement)
Modifies configured logo width/height to ensure they are present and scaleable with different font-si...
Definition: ResourceLoaderSkinModule.php:543
ResourceLoaderSkinModule\getLogoData
getLogoData(Config $conf)
Definition: ResourceLoaderSkinModule.php:626
ResourceLoaderFileModule\$messages
array $messages
List of message keys used by this module.
Definition: ResourceLoaderFileModule.php:146
ResourceLoaderSkinModule\getAvailableLogos
static getAvailableLogos( $conf)
Return an array of all available logos that a skin may use.
Definition: ResourceLoaderSkinModule.php:567
ResourceLoaderSkinModule\applyFeaturesCompatibility
static applyFeaturesCompatibility(array $features, &$messages='')
Definition: ResourceLoaderSkinModule.php:281
ResourceLoaderFileModule\extractBasePaths
static extractBasePaths(array $options=[], $localBasePath=null, $remoteBasePath=null)
Extract a pair of local and remote base paths from module definition information.
Definition: ResourceLoaderFileModule.php:306
ResourceLoaderSkinModule\FEATURE_FILES
const FEATURE_FILES
Every skin should define which features it would like to reuse for core inside a ResourceLoader modul...
Definition: ResourceLoaderSkinModule.php:116
ResourceLoaderSkinModule\getLogoPreloadlinks
getLogoPreloadlinks()
Helper method for getPreloadLinks()
Definition: ResourceLoaderSkinModule.php:445
ResourceLoaderSkinModule\getStyles
getStyles(ResourceLoaderContext $context)
Definition: ResourceLoaderSkinModule.php:387
ResourceLoaderFileModule\$localBasePath
string $localBasePath
Local base path, see __construct()
Definition: ResourceLoaderFileModule.php:42
ResourceLoaderSkinModule\isKnownEmpty
isKnownEmpty(ResourceLoaderContext $context)
Definition: ResourceLoaderSkinModule.php:667
ResourceLoaderSkinModule\getStyleFiles
getStyleFiles(ResourceLoaderContext $context)
Get styles defined in the module definition, plus any enabled feature styles.
Definition: ResourceLoaderSkinModule.php:334
ResourceLoaderFileModule\$remoteBasePath
string $remoteBasePath
Remote base path, see __construct()
Definition: ResourceLoaderFileModule.php:45
ResourceLoaderSkinModule
Module for skin stylesheets.
Definition: ResourceLoaderSkinModule.php:28
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:234
ResourceLoaderSkinModule\$targets
$targets
All skins are assumed to be compatible with mobile.
Definition: ResourceLoaderSkinModule.php:32
OutputPage\transformResourcePath
static transformResourcePath(Config $config, $path)
Transform path to web-accessible static resource.
Definition: OutputPage.php:3995