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;
36 /** @var string|null */
43 private $modules = [];
46 private $moduleStyles = [];
49 private $moduleScripts = [];
52 private $exemptStates = [];
58 * @param ResourceLoaderContext $context
59 * @param string|null $target [optional] Custom 'target' parameter for the startup module
61 public function __construct( ResourceLoaderContext
$context, $target = null ) {
62 $this->context
= $context;
63 $this->resourceLoader
= $context->getResourceLoader();
64 $this->target
= $target;
68 * Set mw.config variables.
70 * @param array $vars Array of key/value pairs
72 public function setConfig( array $vars ) {
73 foreach ( $vars as $key => $value ) {
74 $this->config
[$key] = $value;
79 * Ensure one or more modules are loaded.
81 * @param array $modules Array of module names
83 public function setModules( array $modules ) {
84 $this->modules
= $modules;
88 * Ensure the styles of one or more modules are loaded.
90 * @deprecated since 1.28
91 * @param array $modules Array of module names
93 public function setModuleStyles( array $modules ) {
94 $this->moduleStyles
= $modules;
98 * Ensure the scripts of one or more modules are loaded.
100 * @deprecated since 1.28
101 * @param array $modules Array of module names
103 public function setModuleScripts( array $modules ) {
104 $this->moduleScripts
= $modules;
108 * Set state of special modules that are handled by the caller manually.
110 * See OutputPage::buildExemptModules() for use cases.
112 * @param array $states Module state keyed by module name
114 public function setExemptStates( array $states ) {
115 $this->exemptStates
= $states;
121 private function getData() {
123 // @codeCoverageIgnoreStart
125 // @codeCoverageIgnoreEnd
128 $rl = $this->resourceLoader
;
131 // moduleName => state
138 // Embedding for private modules
146 foreach ( $this->modules
as $name ) {
147 $module = $rl->getModule( $name );
152 $context = $this->getContext( $module->getGroup(), ResourceLoaderModule
::TYPE_COMBINED
);
153 if ( $module->isKnownEmpty( $context ) ) {
154 // Avoid needless request or embed for empty module
155 $data['states'][$name] = 'ready';
159 if ( $module->shouldEmbedModule( $this->context
) ) {
160 // Embed via mw.loader.implement per T36907.
161 $data['embed']['general'][] = $name;
162 // Avoid duplicate request from mw.loader
163 $data['states'][$name] = 'loading';
165 // Load via mw.loader.load()
166 $data['general'][] = $name;
170 foreach ( $this->moduleStyles
as $name ) {
171 $module = $rl->getModule( $name );
176 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
177 $logger = $rl->getLogger();
178 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
184 // Stylesheet doesn't trigger mw.loader callback.
185 // Set "ready" state to allow dependencies and avoid duplicate requests. (T87871)
186 $data['states'][$name] = 'ready';
188 $group = $module->getGroup();
189 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
190 if ( $module->isKnownEmpty( $context ) ) {
191 // Avoid needless request for empty module
192 $data['states'][$name] = 'ready';
194 if ( $module->shouldEmbedModule( $this->context
) ) {
195 // Embed via style element
196 $data['embed']['styles'][] = $name;
197 // Avoid duplicate request from mw.loader
198 $data['states'][$name] = 'ready';
200 // Load from load.php?only=styles via <link rel=stylesheet>
201 $data['styles'][] = $name;
206 foreach ( $this->moduleScripts
as $name ) {
207 $module = $rl->getModule( $name );
212 $group = $module->getGroup();
213 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
214 if ( $module->isKnownEmpty( $context ) ) {
215 // Avoid needless request for empty module
216 $data['states'][$name] = 'ready';
218 // Load from load.php?only=scripts via <script src></script>
219 $data['scripts'][] = $name;
221 // Avoid duplicate request from mw.loader
222 $data['states'][$name] = 'loading';
230 * @return array Attribute key-value pairs for the HTML document element
232 public function getDocumentAttributes() {
233 return [ 'class' => 'client-nojs' ];
237 * The order of elements in the head is as follows:
240 * - Async external script-src.
243 * - Script execution may be blocked on preceeding stylesheets.
244 * - Async scripts are not blocked on stylesheets.
245 * - Inline scripts can't be asynchronous.
246 * - For styles, earlier is better.
248 * @return string|WrappedStringList HTML
250 public function getHeadHtml() {
251 $data = $this->getData();
254 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
255 // This happens synchronously on every page view to avoid flashes of wrong content.
256 // See also #getDocumentAttributes() and /resources/src/startup.js.
257 $chunks[] = Html
::inlineScript(
258 'document.documentElement.className = document.documentElement.className'
259 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
262 // Inline RLQ: Set page variables
263 if ( $this->config
) {
264 $chunks[] = ResourceLoader
::makeInlineScript(
265 ResourceLoader
::makeConfigSetScript( $this->config
)
269 // Inline RLQ: Initial module states
270 $states = array_merge( $this->exemptStates
, $data['states'] );
272 $chunks[] = ResourceLoader
::makeInlineScript(
273 ResourceLoader
::makeLoaderStateScript( $states )
277 // Inline RLQ: Embedded modules
278 if ( $data['embed']['general'] ) {
279 $chunks[] = $this->getLoad(
280 $data['embed']['general'],
281 ResourceLoaderModule
::TYPE_COMBINED
285 // Inline RLQ: Load general modules
286 if ( $data['general'] ) {
287 $chunks[] = ResourceLoader
::makeInlineScript(
288 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
292 // Inline RLQ: Load only=scripts
293 if ( $data['scripts'] ) {
294 $chunks[] = $this->getLoad(
296 ResourceLoaderModule
::TYPE_SCRIPTS
300 // External stylesheets
301 if ( $data['styles'] ) {
302 $chunks[] = $this->getLoad(
304 ResourceLoaderModule
::TYPE_STYLES
308 // Inline stylesheets (embedded only=styles)
309 if ( $data['embed']['styles'] ) {
310 $chunks[] = $this->getLoad(
311 $data['embed']['styles'],
312 ResourceLoaderModule
::TYPE_STYLES
316 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
317 // Pass-through a custom target from OutputPage (T143066).
318 $startupQuery = $this->target ?
[ 'target' => $this->target
] : [];
319 $chunks[] = $this->getLoad(
321 ResourceLoaderModule
::TYPE_SCRIPTS
,
325 return WrappedStringList
::join( "\n", $chunks );
329 * @return string|WrappedStringList HTML
331 public function getBodyHtml() {
335 private function getContext( $group, $type ) {
336 return self
::makeContext( $this->context
, $group, $type );
339 private function getLoad( $modules, $only, array $extraQuery = [] ) {
340 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery );
343 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
344 array $extraQuery = []
346 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
347 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
348 // Set 'only' if not combined
349 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
350 // Remove user parameter in most cases
351 if ( $group !== 'user' && $group !== 'private' ) {
352 $req->setVal( 'user', null );
354 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
355 // Allow caller to setVersion() and setModules()
356 return new DerivativeResourceLoaderContext( $context );
360 * Explicily load or embed modules on a page.
362 * @param ResourceLoaderContext $mainContext
363 * @param array $modules One or more module names
364 * @param string $only ResourceLoaderModule TYPE_ class constant
365 * @param array $extraQuery [optional] Array with extra query parameters for the request
366 * @return string|WrappedStringList HTML
368 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
369 array $extraQuery = []
371 $rl = $mainContext->getResourceLoader();
374 // Sort module names so requests are more uniform
377 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
379 // Recursively call us for every item
380 foreach ( $modules as $name ) {
381 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
383 return new WrappedStringList( "\n", $chunks );
386 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
388 foreach ( $modules as $name ) {
389 $module = $rl->getModule( $name );
391 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
394 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
397 foreach ( $sortedModules as $source => $groups ) {
398 foreach ( $groups as $group => $grpModules ) {
399 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
401 // Separate sets of linked and embedded modules while preserving order
404 foreach ( $grpModules as $name => $module ) {
405 $shouldEmbed = $module->shouldEmbedModule( $context );
406 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
407 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
409 $moduleSets[$idx][1][$name] = $module;
412 // Link/embed each set
413 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
414 $context->setModules( array_keys( $moduleSet ) );
416 // Decide whether to use style or script element
417 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
418 $chunks[] = Html
::inlineStyle(
419 $rl->makeModuleResponse( $context, $moduleSet )
422 $chunks[] = ResourceLoader
::makeInlineScript(
423 $rl->makeModuleResponse( $context, $moduleSet )
427 // See if we have one or more raw modules
429 foreach ( $moduleSet as $key => $module ) {
430 $isRaw |
= $module->isRaw();
433 // Special handling for the user group; because users might change their stuff
434 // on-wiki like user pages, or user preferences; we need to find the highest
435 // timestamp of these user-changeable modules so we can ensure cache misses on change
436 // This should NOT be done for the site group (T29564) because anons get that too
437 // and we shouldn't be putting timestamps in CDN-cached HTML
438 if ( $group === 'user' ) {
439 // Must setModules() before makeVersionQuery()
440 $context->setVersion( $rl->makeVersionQuery( $context ) );
443 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
445 // Decide whether to use 'style' or 'script' element
446 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
447 $chunk = Html
::linkedStyle( $url );
449 if ( $context->getRaw() ||
$isRaw ) {
450 $chunk = Html
::element( 'script', [
451 // In SpecialJavaScriptTest, QUnit must load synchronous
452 'async' => !isset( $extraQuery['sync'] ),
456 $chunk = ResourceLoader
::makeInlineScript(
457 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
462 if ( $group == 'noscript' ) {
463 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
472 return new WrappedStringList( "\n", $chunks );