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 WrappedString\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 aray $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 $modules 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
134 // position => [ moduleName ]
142 // position => [ moduleName ]
146 // Embedding for private modules
157 foreach ( $this->modules
as $name ) {
158 $module = $rl->getModule( $name );
163 $group = $module->getGroup();
164 $position = $module->getPosition();
166 if ( $group === 'private' ) {
167 // Embed via mw.loader.implement per T36907.
168 $data['embed']['general'][$position][] = $name;
169 // Avoid duplicate request from mw.loader
170 $data['states'][$name] = 'loading';
172 // Load via mw.loader.load()
173 $data['general'][$position][] = $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->debug( 'Unexpected general module "{module}" in styles queue.', [
189 // Stylesheet doesn't trigger mw.loader callback.
190 // Set "ready" state to allow dependencies and avoid duplicate requests. (T87871)
191 $data['states'][$name] = 'ready';
194 $group = $module->getGroup();
195 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
196 if ( $module->isKnownEmpty( $context ) ) {
197 // Avoid needless request for empty module
198 $data['states'][$name] = 'ready';
200 if ( $group === 'private' ) {
201 // Embed via style element
202 $data['embed']['styles'][] = $name;
203 // Avoid duplicate request from mw.loader
204 $data['states'][$name] = 'ready';
206 // Load from load.php?only=styles via <link rel=stylesheet>
207 $data['styles'][] = $name;
212 foreach ( $this->moduleScripts
as $name ) {
213 $module = $rl->getModule( $name );
218 $group = $module->getGroup();
219 $position = $module->getPosition();
220 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
221 if ( $module->isKnownEmpty( $context ) ) {
222 // Avoid needless request for empty module
223 $data['states'][$name] = 'ready';
225 // Load from load.php?only=scripts via <script src></script>
226 $data['scripts'][$position][] = $name;
228 // Avoid duplicate request from mw.loader
229 $data['states'][$name] = 'loading';
237 * @return array Attribute key-value pairs for the HTML document element
239 public function getDocumentAttributes() {
240 return [ 'class' => 'client-nojs' ];
244 * The order of elements in the head is as follows:
247 * - Async external script-src.
250 * - Script execution may be blocked on preceeding stylesheets.
251 * - Async scripts are not blocked on stylesheets.
252 * - Inline scripts can't be asynchronous.
253 * - For styles, earlier is better.
255 * @return string|WrappedStringList HTML
257 public function getHeadHtml() {
258 $data = $this->getData();
261 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
262 // This happens synchronously on every page view to avoid flashes of wrong content.
263 // See also #getDocumentAttributes() and /resources/src/startup.js.
264 $chunks[] = Html
::inlineScript(
265 'document.documentElement.className = document.documentElement.className'
266 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
269 // Inline RLQ: Set page variables
270 if ( $this->config
) {
271 $chunks[] = ResourceLoader
::makeInlineScript(
272 ResourceLoader
::makeConfigSetScript( $this->config
)
276 // Inline RLQ: Initial module states
277 $states = array_merge( $this->exemptStates
, $data['states'] );
279 $chunks[] = ResourceLoader
::makeInlineScript(
280 ResourceLoader
::makeLoaderStateScript( $states )
284 // Inline RLQ: Embedded modules
285 if ( $data['embed']['general']['top'] ) {
286 $chunks[] = $this->getLoad(
287 $data['embed']['general']['top'],
288 ResourceLoaderModule
::TYPE_COMBINED
292 // Inline RLQ: Load general modules
293 if ( $data['general']['top'] ) {
294 $chunks[] = ResourceLoader
::makeInlineScript(
295 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general']['top'] ] )
299 // Inline RLQ: Load only=scripts
300 if ( $data['scripts']['top'] ) {
301 $chunks[] = $this->getLoad(
302 $data['scripts']['top'],
303 ResourceLoaderModule
::TYPE_SCRIPTS
307 // External stylesheets
308 if ( $data['styles'] ) {
309 $chunks[] = $this->getLoad(
311 ResourceLoaderModule
::TYPE_STYLES
315 // Inline stylesheets (embedded only=styles)
316 if ( $data['embed']['styles'] ) {
317 $chunks[] = $this->getLoad(
318 $data['embed']['styles'],
319 ResourceLoaderModule
::TYPE_STYLES
323 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
324 // Pass-through a custom target from OutputPage (T143066).
325 $startupQuery = $this->target ?
[ 'target' => $this->target
] : [];
326 $chunks[] = $this->getLoad(
328 ResourceLoaderModule
::TYPE_SCRIPTS
,
332 return WrappedStringList
::join( "\n", $chunks );
336 * @return string|WrappedStringList HTML
338 public function getBodyHtml() {
339 $data = $this->getData();
342 // Inline RLQ: Embedded modules
343 if ( $data['embed']['general']['bottom'] ) {
344 $chunks[] = $this->getLoad(
345 $data['embed']['general']['bottom'],
346 ResourceLoaderModule
::TYPE_COMBINED
350 // Inline RLQ: Load only=scripts
351 if ( $data['scripts']['bottom'] ) {
352 $chunks[] = $this->getLoad(
353 $data['scripts']['bottom'],
354 ResourceLoaderModule
::TYPE_SCRIPTS
358 // Inline RLQ: Load general modules
359 if ( $data['general']['bottom'] ) {
360 $chunks[] = ResourceLoader
::makeInlineScript(
361 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general']['bottom'] ] )
365 return WrappedStringList
::join( "\n", $chunks );
368 private function getContext( $group, $type ) {
369 return self
::makeContext( $this->context
, $group, $type );
372 private function getLoad( $modules, $only, array $extraQuery = [] ) {
373 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery );
376 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
377 array $extraQuery = []
379 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
380 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
381 // Set 'only' if not combined
382 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
383 // Remove user parameter in most cases
384 if ( $group !== 'user' && $group !== 'private' ) {
385 $req->setVal( 'user', null );
387 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
388 // Allow caller to setVersion() and setModules()
389 return new DerivativeResourceLoaderContext( $context );
393 * Explicily load or embed modules on a page.
395 * @param ResourceLoaderContext $mainContext
396 * @param array $modules One or more module names
397 * @param string $only ResourceLoaderModule TYPE_ class constant
398 * @param array $extraQuery [optional] Array with extra query parameters for the request
399 * @return string|WrappedStringList HTML
401 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
402 array $extraQuery = []
404 $rl = $mainContext->getResourceLoader();
407 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
409 // Recursively call us for every item
410 foreach ( $modules as $name ) {
411 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
413 return new WrappedStringList( "\n", $chunks );
416 // Sort module names so requests are more uniform
418 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
420 foreach ( $modules as $name ) {
421 $module = $rl->getModule( $name );
423 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
426 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
429 foreach ( $sortedModules as $source => $groups ) {
430 foreach ( $groups as $group => $grpModules ) {
431 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
432 $context->setModules( array_keys( $grpModules ) );
434 if ( $group === 'private' ) {
435 // Decide whether to use style or script element
436 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
437 $chunks[] = Html
::inlineStyle(
438 $rl->makeModuleResponse( $context, $grpModules )
441 $chunks[] = ResourceLoader
::makeInlineScript(
442 $rl->makeModuleResponse( $context, $grpModules )
448 // See if we have one or more raw modules
450 foreach ( $grpModules as $key => $module ) {
451 $isRaw |
= $module->isRaw();
454 // Special handling for the user group; because users might change their stuff
455 // on-wiki like user pages, or user preferences; we need to find the highest
456 // timestamp of these user-changeable modules so we can ensure cache misses on change
457 // This should NOT be done for the site group (bug 27564) because anons get that too
458 // and we shouldn't be putting timestamps in CDN-cached HTML
459 if ( $group === 'user' ) {
460 // Must setModules() before makeVersionQuery()
461 $context->setVersion( $rl->makeVersionQuery( $context ) );
464 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
466 // Decide whether to use 'style' or 'script' element
467 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
468 $chunk = Html
::linkedStyle( $url );
470 if ( $context->getRaw() ||
$isRaw ) {
471 $chunk = Html
::element( 'script', [
472 // In SpecialJavaScriptTest, QUnit must load synchronous
473 'async' => !isset( $extraQuery['sync'] ),
477 $chunk = ResourceLoader
::makeInlineScript(
478 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
483 if ( $group == 'noscript' ) {
484 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
491 return new WrappedStringList( "\n", $chunks );