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
145 foreach ( $this->modules
as $name ) {
146 $module = $rl->getModule( $name );
151 $group = $module->getGroup();
152 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
153 if ( $module->isKnownEmpty( $context ) ) {
154 // Avoid needless request or embed for empty module
155 $data['states'][$name] = 'ready';
159 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
160 // Call makeLoad() to decide how to load these, instead of
161 // loading via mw.loader.load().
162 // - For group=user: We need to provide a pre-generated load.php
163 // url to the client that has the 'user' and 'version' parameters
164 // filled in. Without this, the client would wrongly use the static
165 // version hash, per T64602.
166 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
167 $data['embed']['general'][] = $name;
168 // Avoid duplicate request from mw.loader
169 $data['states'][$name] = 'loading';
171 // Load via mw.loader.load()
172 $data['general'][] = $name;
176 foreach ( $this->moduleStyles
as $name ) {
177 $module = $rl->getModule( $name );
182 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
183 $logger = $rl->getLogger();
184 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
190 // Stylesheet doesn't trigger mw.loader callback.
191 // Set "ready" state to allow script modules to depend on this module (T87871).
192 // And to avoid duplicate requests at run-time from mw.loader.
193 $data['states'][$name] = 'ready';
195 $group = $module->getGroup();
196 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
197 // Avoid needless request for empty module
198 if ( !$module->isKnownEmpty( $context ) ) {
199 if ( $module->shouldEmbedModule( $this->context
) ) {
200 // Embed via style element
201 $data['embed']['styles'][] = $name;
203 // Load from load.php?only=styles via <link rel=stylesheet>
204 $data['styles'][] = $name;
209 foreach ( $this->moduleScripts
as $name ) {
210 $module = $rl->getModule( $name );
215 $group = $module->getGroup();
216 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
217 if ( $module->isKnownEmpty( $context ) ) {
218 // Avoid needless request for empty module
219 $data['states'][$name] = 'ready';
221 // Load from load.php?only=scripts via <script src></script>
222 $data['scripts'][] = $name;
224 // Avoid duplicate request from mw.loader
225 $data['states'][$name] = 'loading';
233 * @return array Attribute key-value pairs for the HTML document element
235 public function getDocumentAttributes() {
236 return [ 'class' => 'client-nojs' ];
240 * The order of elements in the head is as follows:
243 * - Async external script-src.
246 * - Script execution may be blocked on preceeding stylesheets.
247 * - Async scripts are not blocked on stylesheets.
248 * - Inline scripts can't be asynchronous.
249 * - For styles, earlier is better.
251 * @return string|WrappedStringList HTML
253 public function getHeadHtml() {
254 $data = $this->getData();
257 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
258 // This happens synchronously on every page view to avoid flashes of wrong content.
259 // See also #getDocumentAttributes() and /resources/src/startup.js.
260 $chunks[] = Html
::inlineScript(
261 'document.documentElement.className = document.documentElement.className'
262 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
265 // Inline RLQ: Set page variables
266 if ( $this->config
) {
267 $chunks[] = ResourceLoader
::makeInlineScript(
268 ResourceLoader
::makeConfigSetScript( $this->config
)
272 // Inline RLQ: Initial module states
273 $states = array_merge( $this->exemptStates
, $data['states'] );
275 $chunks[] = ResourceLoader
::makeInlineScript(
276 ResourceLoader
::makeLoaderStateScript( $states )
280 // Inline RLQ: Embedded modules
281 if ( $data['embed']['general'] ) {
282 $chunks[] = $this->getLoad(
283 $data['embed']['general'],
284 ResourceLoaderModule
::TYPE_COMBINED
288 // Inline RLQ: Load general modules
289 if ( $data['general'] ) {
290 $chunks[] = ResourceLoader
::makeInlineScript(
291 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
295 // Inline RLQ: Load only=scripts
296 if ( $data['scripts'] ) {
297 $chunks[] = $this->getLoad(
299 ResourceLoaderModule
::TYPE_SCRIPTS
303 // External stylesheets
304 if ( $data['styles'] ) {
305 $chunks[] = $this->getLoad(
307 ResourceLoaderModule
::TYPE_STYLES
311 // Inline stylesheets (embedded only=styles)
312 if ( $data['embed']['styles'] ) {
313 $chunks[] = $this->getLoad(
314 $data['embed']['styles'],
315 ResourceLoaderModule
::TYPE_STYLES
319 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
320 // Pass-through a custom 'target' from OutputPage (T143066).
321 $startupQuery = isset( $this->options
['target'] )
322 ?
[ 'target' => (string)$this->options
['target'] ]
324 $chunks[] = $this->getLoad(
326 ResourceLoaderModule
::TYPE_SCRIPTS
,
330 return WrappedStringList
::join( "\n", $chunks );
334 * @return string|WrappedStringList HTML
336 public function getBodyHtml() {
340 private function getContext( $group, $type ) {
341 return self
::makeContext( $this->context
, $group, $type );
344 private function getLoad( $modules, $only, array $extraQuery = [] ) {
345 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery );
348 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
349 array $extraQuery = []
351 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
352 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
353 // Set 'only' if not combined
354 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
355 // Remove user parameter in most cases
356 if ( $group !== 'user' && $group !== 'private' ) {
357 $req->setVal( 'user', null );
359 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
360 // Allow caller to setVersion() and setModules()
361 return new DerivativeResourceLoaderContext( $context );
365 * Explicily load or embed modules on a page.
367 * @param ResourceLoaderContext $mainContext
368 * @param array $modules One or more module names
369 * @param string $only ResourceLoaderModule TYPE_ class constant
370 * @param array $extraQuery [optional] Array with extra query parameters for the request
371 * @return string|WrappedStringList HTML
373 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
374 array $extraQuery = []
376 $rl = $mainContext->getResourceLoader();
379 // Sort module names so requests are more uniform
382 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
384 // Recursively call us for every item
385 foreach ( $modules as $name ) {
386 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
388 return new WrappedStringList( "\n", $chunks );
391 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
393 foreach ( $modules as $name ) {
394 $module = $rl->getModule( $name );
396 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
399 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
402 foreach ( $sortedModules as $source => $groups ) {
403 foreach ( $groups as $group => $grpModules ) {
404 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
406 // Separate sets of linked and embedded modules while preserving order
409 foreach ( $grpModules as $name => $module ) {
410 $shouldEmbed = $module->shouldEmbedModule( $context );
411 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
412 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
414 $moduleSets[$idx][1][$name] = $module;
417 // Link/embed each set
418 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
419 $context->setModules( array_keys( $moduleSet ) );
421 // Decide whether to use style or script element
422 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
423 $chunks[] = Html
::inlineStyle(
424 $rl->makeModuleResponse( $context, $moduleSet )
427 $chunks[] = ResourceLoader
::makeInlineScript(
428 $rl->makeModuleResponse( $context, $moduleSet )
432 // See if we have one or more raw modules
434 foreach ( $moduleSet as $key => $module ) {
435 $isRaw |
= $module->isRaw();
438 // Special handling for the user group; because users might change their stuff
439 // on-wiki like user pages, or user preferences; we need to find the highest
440 // timestamp of these user-changeable modules so we can ensure cache misses on change
441 // This should NOT be done for the site group (T29564) because anons get that too
442 // and we shouldn't be putting timestamps in CDN-cached HTML
443 if ( $group === 'user' ) {
444 // Must setModules() before makeVersionQuery()
445 $context->setVersion( $rl->makeVersionQuery( $context ) );
448 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
450 // Decide whether to use 'style' or 'script' element
451 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
452 $chunk = Html
::linkedStyle( $url );
454 if ( $context->getRaw() ||
$isRaw ) {
455 $chunk = Html
::element( 'script', [
456 // In SpecialJavaScriptTest, QUnit must load synchronous
457 'async' => !isset( $extraQuery['sync'] ),
461 $chunk = ResourceLoader
::makeInlineScript(
462 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
467 if ( $group == 'noscript' ) {
468 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
477 return new WrappedStringList( "\n", $chunks );