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.
62 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
63 $this->context
= $context;
64 $this->resourceLoader
= $context->getResourceLoader();
65 $this->options
= $options;
69 * Set mw.config variables.
71 * @param array $vars Array of key/value pairs
73 public function setConfig( array $vars ) {
74 foreach ( $vars as $key => $value ) {
75 $this->config
[$key] = $value;
80 * Ensure one or more modules are loaded.
82 * @param array $modules Array of module names
84 public function setModules( array $modules ) {
85 $this->modules
= $modules;
89 * Ensure the styles of one or more modules are loaded.
91 * @deprecated since 1.28
92 * @param array $modules Array of module names
94 public function setModuleStyles( array $modules ) {
95 $this->moduleStyles
= $modules;
99 * Ensure the scripts of one or more modules are loaded.
101 * @deprecated since 1.28
102 * @param array $modules Array of module names
104 public function setModuleScripts( array $modules ) {
105 $this->moduleScripts
= $modules;
109 * Set state of special modules that are handled by the caller manually.
111 * See OutputPage::buildExemptModules() for use cases.
113 * @param array $states Module state keyed by module name
115 public function setExemptStates( array $states ) {
116 $this->exemptStates
= $states;
122 private function getData() {
124 // @codeCoverageIgnoreStart
126 // @codeCoverageIgnoreEnd
129 $rl = $this->resourceLoader
;
132 // moduleName => state
137 // Embedding for private modules
142 // Deprecations for style-only modules
143 'styledeprecations' => [],
146 foreach ( $this->modules
as $name ) {
147 $module = $rl->getModule( $name );
152 $group = $module->getGroup();
153 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
154 if ( $module->isKnownEmpty( $context ) ) {
155 // Avoid needless request or embed for empty module
156 $data['states'][$name] = 'ready';
160 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
161 // Call makeLoad() to decide how to load these, instead of
162 // loading via mw.loader.load().
163 // - For group=user: We need to provide a pre-generated load.php
164 // url to the client that has the 'user' and 'version' parameters
165 // filled in. Without this, the client would wrongly use the static
166 // version hash, per T64602.
167 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
168 $data['embed']['general'][] = $name;
169 // Avoid duplicate request from mw.loader
170 $data['states'][$name] = 'loading';
172 // Load via mw.loader.load()
173 $data['general'][] = $name;
177 foreach ( $this->moduleStyles
as $name ) {
178 $module = $rl->getModule( $name );
183 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
184 $logger = $rl->getLogger();
185 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
191 // Stylesheet doesn't trigger mw.loader callback.
192 // Set "ready" state to allow script modules to depend on this module (T87871).
193 // And to avoid duplicate requests at run-time from mw.loader.
194 $data['states'][$name] = 'ready';
196 $group = $module->getGroup();
197 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
198 // Avoid needless request for empty module
199 if ( !$module->isKnownEmpty( $context ) ) {
200 if ( $module->shouldEmbedModule( $this->context
) ) {
201 // Embed via style element
202 $data['embed']['styles'][] = $name;
204 // Load from load.php?only=styles via <link rel=stylesheet>
205 $data['styles'][] = $name;
208 $deprecation = $module->getDeprecationInformation();
209 if ( $deprecation ) {
210 $data['styledeprecations'][] = $deprecation;
214 foreach ( $this->moduleScripts
as $name ) {
215 $module = $rl->getModule( $name );
220 $group = $module->getGroup();
221 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
222 if ( $module->isKnownEmpty( $context ) ) {
223 // Avoid needless request for empty module
224 $data['states'][$name] = 'ready';
226 // Load from load.php?only=scripts via <script src></script>
227 $data['scripts'][] = $name;
229 // Avoid duplicate request from mw.loader
230 $data['states'][$name] = 'loading';
238 * @return array Attribute key-value pairs for the HTML document element
240 public function getDocumentAttributes() {
241 return [ 'class' => 'client-nojs' ];
245 * The order of elements in the head is as follows:
248 * - Async external script-src.
251 * - Script execution may be blocked on preceeding stylesheets.
252 * - Async scripts are not blocked on stylesheets.
253 * - Inline scripts can't be asynchronous.
254 * - For styles, earlier is better.
256 * @param string $nonce From OutputPage::getCSPNonce()
257 * @return string|WrappedStringList HTML
259 public function getHeadHtml( $nonce ) {
260 $data = $this->getData();
263 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
264 // This happens synchronously on every page view to avoid flashes of wrong content.
265 // See also #getDocumentAttributes() and /resources/src/startup.js.
266 $chunks[] = Html
::inlineScript(
267 'document.documentElement.className = document.documentElement.className'
268 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
272 // Inline RLQ: Set page variables
273 if ( $this->config
) {
274 $chunks[] = ResourceLoader
::makeInlineScript(
275 ResourceLoader
::makeConfigSetScript( $this->config
),
280 // Inline RLQ: Initial module states
281 $states = array_merge( $this->exemptStates
, $data['states'] );
283 $chunks[] = ResourceLoader
::makeInlineScript(
284 ResourceLoader
::makeLoaderStateScript( $states ),
289 // Inline RLQ: Embedded modules
290 if ( $data['embed']['general'] ) {
291 $chunks[] = $this->getLoad(
292 $data['embed']['general'],
293 ResourceLoaderModule
::TYPE_COMBINED
,
298 // Inline RLQ: Load general modules
299 if ( $data['general'] ) {
300 $chunks[] = ResourceLoader
::makeInlineScript(
301 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
306 // Inline RLQ: Load only=scripts
307 if ( $data['scripts'] ) {
308 $chunks[] = $this->getLoad(
310 ResourceLoaderModule
::TYPE_SCRIPTS
,
315 // Deprecations for only=styles modules
316 if ( $data['styledeprecations'] ) {
317 $chunks[] = ResourceLoader
::makeInlineScript(
318 implode( '', $data['styledeprecations'] ),
323 // External stylesheets (only=styles)
324 if ( $data['styles'] ) {
325 $chunks[] = $this->getLoad(
327 ResourceLoaderModule
::TYPE_STYLES
,
332 // Inline stylesheets (embedded only=styles)
333 if ( $data['embed']['styles'] ) {
334 $chunks[] = $this->getLoad(
335 $data['embed']['styles'],
336 ResourceLoaderModule
::TYPE_STYLES
,
341 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
342 // Pass-through a custom 'target' from OutputPage (T143066).
343 $startupQuery = isset( $this->options
['target'] )
344 ?
[ 'target' => (string)$this->options
['target'] ]
346 $chunks[] = $this->getLoad(
348 ResourceLoaderModule
::TYPE_SCRIPTS
,
353 return WrappedStringList
::join( "\n", $chunks );
357 * @return string|WrappedStringList HTML
359 public function getBodyHtml() {
363 private function getContext( $group, $type ) {
364 return self
::makeContext( $this->context
, $group, $type );
367 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
368 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
371 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
372 array $extraQuery = []
374 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
375 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
376 // Set 'only' if not combined
377 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
378 // Remove user parameter in most cases
379 if ( $group !== 'user' && $group !== 'private' ) {
380 $req->setVal( 'user', null );
382 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
383 // Allow caller to setVersion() and setModules()
384 $ret = new DerivativeResourceLoaderContext( $context );
385 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
390 * Explicily load or embed modules on a page.
392 * @param ResourceLoaderContext $mainContext
393 * @param array $modules One or more module names
394 * @param string $only ResourceLoaderModule TYPE_ class constant
395 * @param array $extraQuery Array with extra query parameters for the request
396 * @param string $nonce See OutputPage::getCSPNonce() [Since 1.32]
397 * @return string|WrappedStringList HTML
399 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
400 array $extraQuery, $nonce
402 $rl = $mainContext->getResourceLoader();
405 // Sort module names so requests are more uniform
408 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
410 // Recursively call us for every item
411 foreach ( $modules as $name ) {
412 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
414 return new WrappedStringList( "\n", $chunks );
417 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
419 foreach ( $modules as $name ) {
420 $module = $rl->getModule( $name );
422 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
425 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
428 foreach ( $sortedModules as $source => $groups ) {
429 foreach ( $groups as $group => $grpModules ) {
430 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
432 // Separate sets of linked and embedded modules while preserving order
435 foreach ( $grpModules as $name => $module ) {
436 $shouldEmbed = $module->shouldEmbedModule( $context );
437 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
438 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
440 $moduleSets[$idx][1][$name] = $module;
443 // Link/embed each set
444 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
445 $context->setModules( array_keys( $moduleSet ) );
447 // Decide whether to use style or script element
448 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
449 $chunks[] = Html
::inlineStyle(
450 $rl->makeModuleResponse( $context, $moduleSet )
453 $chunks[] = ResourceLoader
::makeInlineScript(
454 $rl->makeModuleResponse( $context, $moduleSet ),
459 // See if we have one or more raw modules
461 foreach ( $moduleSet as $key => $module ) {
462 $isRaw |
= $module->isRaw();
465 // Special handling for the user group; because users might change their stuff
466 // on-wiki like user pages, or user preferences; we need to find the highest
467 // timestamp of these user-changeable modules so we can ensure cache misses on change
468 // This should NOT be done for the site group (T29564) because anons get that too
469 // and we shouldn't be putting timestamps in CDN-cached HTML
470 if ( $group === 'user' ) {
471 // Must setModules() before makeVersionQuery()
472 $context->setVersion( $rl->makeVersionQuery( $context ) );
475 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
477 // Decide whether to use 'style' or 'script' element
478 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
479 $chunk = Html
::linkedStyle( $url );
481 if ( $context->getRaw() ||
$isRaw ) {
482 $chunk = Html
::element( 'script', [
483 // In SpecialJavaScriptTest, QUnit must load synchronous
484 'async' => !isset( $extraQuery['sync'] ),
488 $chunk = ResourceLoader
::makeInlineScript(
489 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
495 if ( $group == 'noscript' ) {
496 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
505 return new WrappedStringList( "\n", $chunks );