3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use Wikimedia\WrappedStringList
;
24 * Bootstrap a ResourceLoader client on an HTML page.
28 class ResourceLoaderClientHtml
{
30 /** @var ResourceLoaderContext */
33 /** @var ResourceLoader */
34 private $resourceLoader;
43 private $modules = [];
46 private $moduleStyles = [];
49 private $moduleScripts = [];
52 private $exemptStates = [];
58 * @param ResourceLoaderContext $context
59 * @param array $options [optional] Array of options
60 * - 'target': Custom parameter passed to StartupModule.
61 * - 'nonce': From OutputPage::getCSPNonce().
63 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
64 $this->context
= $context;
65 $this->resourceLoader
= $context->getResourceLoader();
66 $this->options
= $options +
[
73 * Set mw.config variables.
75 * @param array $vars Array of key/value pairs
77 public function setConfig( array $vars ) {
78 foreach ( $vars as $key => $value ) {
79 $this->config
[$key] = $value;
84 * Ensure one or more modules are loaded.
86 * @param array $modules Array of module names
88 public function setModules( array $modules ) {
89 $this->modules
= $modules;
93 * Ensure the styles of one or more modules are loaded.
95 * @deprecated since 1.28
96 * @param array $modules Array of module names
98 public function setModuleStyles( array $modules ) {
99 $this->moduleStyles
= $modules;
103 * Ensure the scripts of one or more modules are loaded.
105 * @deprecated since 1.28
106 * @param array $modules Array of module names
108 public function setModuleScripts( array $modules ) {
109 $this->moduleScripts
= $modules;
113 * Set state of special modules that are handled by the caller manually.
115 * See OutputPage::buildExemptModules() for use cases.
117 * @param array $states Module state keyed by module name
119 public function setExemptStates( array $states ) {
120 $this->exemptStates
= $states;
126 private function getData() {
128 // @codeCoverageIgnoreStart
130 // @codeCoverageIgnoreEnd
133 $rl = $this->resourceLoader
;
136 // moduleName => state
141 // Embedding for private modules
146 // Deprecations for style-only modules
147 'styledeprecations' => [],
150 foreach ( $this->modules
as $name ) {
151 $module = $rl->getModule( $name );
156 $group = $module->getGroup();
157 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
158 if ( $module->isKnownEmpty( $context ) ) {
159 // Avoid needless request or embed for empty module
160 $data['states'][$name] = 'ready';
164 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
165 // Call makeLoad() to decide how to load these, instead of
166 // loading via mw.loader.load().
167 // - For group=user: We need to provide a pre-generated load.php
168 // url to the client that has the 'user' and 'version' parameters
169 // filled in. Without this, the client would wrongly use the static
170 // version hash, per T64602.
171 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
172 $data['embed']['general'][] = $name;
173 // Avoid duplicate request from mw.loader
174 $data['states'][$name] = 'loading';
176 // Load via mw.loader.load()
177 $data['general'][] = $name;
181 foreach ( $this->moduleStyles
as $name ) {
182 $module = $rl->getModule( $name );
187 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
188 $logger = $rl->getLogger();
189 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
195 // Stylesheet doesn't trigger mw.loader callback.
196 // Set "ready" state to allow script modules to depend on this module (T87871).
197 // And to avoid duplicate requests at run-time from mw.loader.
198 $data['states'][$name] = 'ready';
200 $group = $module->getGroup();
201 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
202 // Avoid needless request for empty module
203 if ( !$module->isKnownEmpty( $context ) ) {
204 if ( $module->shouldEmbedModule( $this->context
) ) {
205 // Embed via style element
206 $data['embed']['styles'][] = $name;
208 // Load from load.php?only=styles via <link rel=stylesheet>
209 $data['styles'][] = $name;
212 $deprecation = $module->getDeprecationInformation();
213 if ( $deprecation ) {
214 $data['styledeprecations'][] = $deprecation;
218 foreach ( $this->moduleScripts
as $name ) {
219 $module = $rl->getModule( $name );
224 $group = $module->getGroup();
225 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
226 if ( $module->isKnownEmpty( $context ) ) {
227 // Avoid needless request for empty module
228 $data['states'][$name] = 'ready';
230 // Load from load.php?only=scripts via <script src></script>
231 $data['scripts'][] = $name;
233 // Avoid duplicate request from mw.loader
234 $data['states'][$name] = 'loading';
242 * @return array Attribute key-value pairs for the HTML document element
244 public function getDocumentAttributes() {
245 return [ 'class' => 'client-nojs' ];
249 * The order of elements in the head is as follows:
252 * - Async external script-src.
255 * - Script execution may be blocked on preceeding stylesheets.
256 * - Async scripts are not blocked on stylesheets.
257 * - Inline scripts can't be asynchronous.
258 * - For styles, earlier is better.
260 * @return string|WrappedStringList HTML
262 public function getHeadHtml() {
263 $nonce = $this->options
['nonce'];
264 $data = $this->getData();
267 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
268 // This happens synchronously on every page view to avoid flashes of wrong content.
269 // See also #getDocumentAttributes() and /resources/src/startup.js.
270 $chunks[] = Html
::inlineScript(
271 'document.documentElement.className = document.documentElement.className'
272 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
276 // Inline RLQ: Set page variables
277 if ( $this->config
) {
278 $chunks[] = ResourceLoader
::makeInlineScript(
279 ResourceLoader
::makeConfigSetScript( $this->config
),
284 // Inline RLQ: Initial module states
285 $states = array_merge( $this->exemptStates
, $data['states'] );
287 $chunks[] = ResourceLoader
::makeInlineScript(
288 ResourceLoader
::makeLoaderStateScript( $states ),
293 // Inline RLQ: Embedded modules
294 if ( $data['embed']['general'] ) {
295 $chunks[] = $this->getLoad(
296 $data['embed']['general'],
297 ResourceLoaderModule
::TYPE_COMBINED
,
302 // Inline RLQ: Load general modules
303 if ( $data['general'] ) {
304 $chunks[] = ResourceLoader
::makeInlineScript(
305 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
310 // Inline RLQ: Load only=scripts
311 if ( $data['scripts'] ) {
312 $chunks[] = $this->getLoad(
314 ResourceLoaderModule
::TYPE_SCRIPTS
,
319 // Deprecations for only=styles modules
320 if ( $data['styledeprecations'] ) {
321 $chunks[] = ResourceLoader
::makeInlineScript(
322 implode( '', $data['styledeprecations'] ),
327 // External stylesheets (only=styles)
328 if ( $data['styles'] ) {
329 $chunks[] = $this->getLoad(
331 ResourceLoaderModule
::TYPE_STYLES
,
336 // Inline stylesheets (embedded only=styles)
337 if ( $data['embed']['styles'] ) {
338 $chunks[] = $this->getLoad(
339 $data['embed']['styles'],
340 ResourceLoaderModule
::TYPE_STYLES
,
345 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
346 // Pass-through a custom 'target' from OutputPage (T143066).
347 $startupQuery = $this->options
['target'] !== null
348 ?
[ 'target' => (string)$this->options
['target'] ]
350 $chunks[] = $this->getLoad(
352 ResourceLoaderModule
::TYPE_SCRIPTS
,
357 return WrappedStringList
::join( "\n", $chunks );
361 * @return string|WrappedStringList HTML
363 public function getBodyHtml() {
367 private function getContext( $group, $type ) {
368 return self
::makeContext( $this->context
, $group, $type );
371 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
372 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
375 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
376 array $extraQuery = []
378 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
379 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
380 // Set 'only' if not combined
381 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
382 // Remove user parameter in most cases
383 if ( $group !== 'user' && $group !== 'private' ) {
384 $req->setVal( 'user', null );
386 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
387 // Allow caller to setVersion() and setModules()
388 $ret = new DerivativeResourceLoaderContext( $context );
389 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
394 * Explicily load or embed modules on a page.
396 * @param ResourceLoaderContext $mainContext
397 * @param array $modules One or more module names
398 * @param string $only ResourceLoaderModule TYPE_ class constant
399 * @param array $extraQuery [optional] Array with extra query parameters for the request
400 * @param string $nonce [optional] Content-Security-Policy nonce (from OutputPage::getCSPNonce)
401 * @return string|WrappedStringList HTML
403 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
404 array $extraQuery = [], $nonce = null
406 $rl = $mainContext->getResourceLoader();
409 // Sort module names so requests are more uniform
412 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
414 // Recursively call us for every item
415 foreach ( $modules as $name ) {
416 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
418 return new WrappedStringList( "\n", $chunks );
421 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
423 foreach ( $modules as $name ) {
424 $module = $rl->getModule( $name );
426 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
429 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
432 foreach ( $sortedModules as $source => $groups ) {
433 foreach ( $groups as $group => $grpModules ) {
434 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
436 // Separate sets of linked and embedded modules while preserving order
439 foreach ( $grpModules as $name => $module ) {
440 $shouldEmbed = $module->shouldEmbedModule( $context );
441 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
442 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
444 $moduleSets[$idx][1][$name] = $module;
447 // Link/embed each set
448 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
449 $context->setModules( array_keys( $moduleSet ) );
451 // Decide whether to use style or script element
452 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
453 $chunks[] = Html
::inlineStyle(
454 $rl->makeModuleResponse( $context, $moduleSet )
457 $chunks[] = ResourceLoader
::makeInlineScript(
458 $rl->makeModuleResponse( $context, $moduleSet ),
463 // See if we have one or more raw modules
465 foreach ( $moduleSet as $key => $module ) {
466 $isRaw |
= $module->isRaw();
469 // Special handling for the user group; because users might change their stuff
470 // on-wiki like user pages, or user preferences; we need to find the highest
471 // timestamp of these user-changeable modules so we can ensure cache misses on change
472 // This should NOT be done for the site group (T29564) because anons get that too
473 // and we shouldn't be putting timestamps in CDN-cached HTML
474 if ( $group === 'user' ) {
475 // Must setModules() before makeVersionQuery()
476 $context->setVersion( $rl->makeVersionQuery( $context ) );
479 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
481 // Decide whether to use 'style' or 'script' element
482 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
483 $chunk = Html
::linkedStyle( $url );
485 if ( $context->getRaw() ||
$isRaw ) {
486 $chunk = Html
::element( 'script', [
487 // In SpecialJavaScriptTest, QUnit must load synchronous
488 'async' => !isset( $extraQuery['sync'] ),
492 $chunk = ResourceLoader
::makeInlineScript(
493 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
499 if ( $group == 'noscript' ) {
500 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
509 return new WrappedStringList( "\n", $chunks );