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;
40 private $modules = [];
43 private $moduleStyles = [];
46 private $moduleScripts = [];
49 private $exemptStates = [];
55 * @param ResourceLoaderContext $context
57 public function __construct( ResourceLoaderContext
$context ) {
58 $this->context
= $context;
59 $this->resourceLoader
= $context->getResourceLoader();
63 * Set mw.config variables.
65 * @param array $vars Array of key/value pairs
67 public function setConfig( array $vars ) {
68 foreach ( $vars as $key => $value ) {
69 $this->config
[$key] = $value;
74 * Ensure one or more modules are loaded.
76 * @param array $modules Array of module names
78 public function setModules( array $modules ) {
79 $this->modules
= $modules;
83 * Ensure the styles of one or more modules are loaded.
85 * @deprecated since 1.28
86 * @param array $modules Array of module names
88 public function setModuleStyles( array $modules ) {
89 $this->moduleStyles
= $modules;
93 * Ensure the scripts of one or more modules are loaded.
95 * @deprecated since 1.28
96 * @param array $modules Array of module names
98 public function setModuleScripts( array $modules ) {
99 $this->moduleScripts
= $modules;
103 * Set state of special modules that are handled by the caller manually.
105 * See OutputPage::buildExemptModules() for use cases.
107 * @param array $modules Module state keyed by module name
109 public function setExemptStates( array $states ) {
110 $this->exemptStates
= $states;
116 private function getData() {
118 // @codeCoverageIgnoreStart
120 // @codeCoverageIgnoreEnd
123 $rl = $this->resourceLoader
;
126 // moduleName => state
129 // position => [ moduleName ]
137 // position => [ moduleName ]
141 // Embedding for private modules
152 foreach ( $this->modules
as $name ) {
153 $module = $rl->getModule( $name );
158 $group = $module->getGroup();
159 $position = $module->getPosition();
161 if ( $group === 'private' ) {
162 // Embed via mw.loader.implement per T36907.
163 $data['embed']['general'][$position][] = $name;
164 // Avoid duplicate request from mw.loader
165 $data['states'][$name] = 'loading';
167 // Load via mw.loader.load()
168 $data['general'][$position][] = $name;
172 foreach ( $this->moduleStyles
as $name ) {
173 $module = $rl->getModule( $name );
178 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
179 $logger = $rl->getLogger();
180 $logger->debug( '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';
189 $group = $module->getGroup();
190 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
191 if ( $module->isKnownEmpty( $context ) ) {
192 // Avoid needless request for empty module
193 $data['states'][$name] = 'ready';
195 if ( $group === 'private' ) {
196 // Embed via style element
197 $data['embed']['styles'][] = $name;
198 // Avoid duplicate request from mw.loader
199 $data['states'][$name] = 'ready';
201 // Load from load.php?only=styles via <link rel=stylesheet>
202 $data['styles'][] = $name;
207 foreach ( $this->moduleScripts
as $name ) {
208 $module = $rl->getModule( $name );
213 $group = $module->getGroup();
214 $position = $module->getPosition();
215 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
216 if ( $module->isKnownEmpty( $context ) ) {
217 // Avoid needless request for empty module
218 $data['states'][$name] = 'ready';
220 // Load from load.php?only=scripts via <script src></script>
221 $data['scripts'][$position][] = $name;
223 // Avoid duplicate request from mw.loader
224 $data['states'][$name] = 'loading';
232 * @return array Attribute key-value pairs for the HTML document element
234 public function getDocumentAttributes() {
235 return [ 'class' => 'client-nojs' ];
239 * The order of elements in the head is as follows:
242 * - Async external script-src.
245 * - Script execution may be blocked on preceeding stylesheets.
246 * - Async scripts are not blocked on stylesheets.
247 * - Inline scripts can't be asynchronous.
248 * - For styles, earlier is better.
250 * @return string|WrappedStringList HTML
252 public function getHeadHtml() {
253 $data = $this->getData();
256 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
257 // This happens synchronously on every page view to avoid flashes of wrong content.
258 // See also #getDocumentAttributes() and /resources/src/startup.js.
259 $chunks[] = Html
::inlineScript(
260 'document.documentElement.className = document.documentElement.className'
261 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
264 // Inline RLQ: Set page variables
265 if ( $this->config
) {
266 $chunks[] = ResourceLoader
::makeInlineScript(
267 ResourceLoader
::makeConfigSetScript( $this->config
)
271 // Inline RLQ: Initial module states
272 $states = array_merge( $this->exemptStates
, $data['states'] );
274 $chunks[] = ResourceLoader
::makeInlineScript(
275 ResourceLoader
::makeLoaderStateScript( $states )
279 // Inline RLQ: Embedded modules
280 if ( $data['embed']['general']['top'] ) {
281 $chunks[] = $this->getLoad(
282 $data['embed']['general']['top'],
283 ResourceLoaderModule
::TYPE_COMBINED
287 // Inline RLQ: Load general modules
288 if ( $data['general']['top'] ) {
289 $chunks[] = ResourceLoader
::makeInlineScript(
290 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general']['top'] ] )
294 // Inline RLQ: Load only=scripts
295 if ( $data['scripts']['top'] ) {
296 $chunks[] = $this->getLoad(
297 $data['scripts']['top'],
298 ResourceLoaderModule
::TYPE_SCRIPTS
302 // External stylesheets
303 if ( $data['styles'] ) {
304 $chunks[] = $this->getLoad(
306 ResourceLoaderModule
::TYPE_STYLES
310 // Inline stylesheets (embedded only=styles)
311 if ( $data['embed']['styles'] ) {
312 $chunks[] = $this->getLoad(
313 $data['embed']['styles'],
314 ResourceLoaderModule
::TYPE_STYLES
318 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
319 $chunks[] = $this->getLoad( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
321 return WrappedStringList
::join( "\n", $chunks );
325 * @return string|WrappedStringList HTML
327 public function getBodyHtml() {
328 $data = $this->getData();
331 // Inline RLQ: Embedded modules
332 if ( $data['embed']['general']['bottom'] ) {
333 $chunks[] = $this->getLoad(
334 $data['embed']['general']['bottom'],
335 ResourceLoaderModule
::TYPE_COMBINED
339 // Inline RLQ: Load only=scripts
340 if ( $data['scripts']['bottom'] ) {
341 $chunks[] = $this->getLoad(
342 $data['scripts']['bottom'],
343 ResourceLoaderModule
::TYPE_SCRIPTS
347 // Inline RLQ: Load general modules
348 if ( $data['general']['bottom'] ) {
349 $chunks[] = ResourceLoader
::makeInlineScript(
350 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general']['bottom'] ] )
354 return WrappedStringList
::join( "\n", $chunks );
357 private function getContext( $group, $type ) {
358 return self
::makeContext( $this->context
, $group, $type );
361 private function getLoad( $modules, $only ) {
362 return self
::makeLoad( $this->context
, (array)$modules, $only );
365 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
366 array $extraQuery = []
368 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
369 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
370 // Set 'only' if not combined
371 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
372 // Remove user parameter in most cases
373 if ( $group !== 'user' && $group !== 'private' ) {
374 $req->setVal( 'user', null );
376 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
377 // Allow caller to setVersion() and setModules()
378 return new DerivativeResourceLoaderContext( $context );
382 * Explicily load or embed modules on a page.
384 * @param ResourceLoaderContext $mainContext
385 * @param array $modules One or more module names
386 * @param string $only ResourceLoaderModule TYPE_ class constant
387 * @param array $extraQuery [optional] Array with extra query parameters for the request
388 * @return string|WrappedStringList HTML
390 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
391 array $extraQuery = []
393 $rl = $mainContext->getResourceLoader();
396 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
398 // Recursively call us for every item
399 foreach ( $modules as $name ) {
400 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
402 return new WrappedStringList( "\n", $chunks );
405 // Sort module names so requests are more uniform
407 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
409 foreach ( $modules as $name ) {
410 $module = $rl->getModule( $name );
412 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
415 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
418 foreach ( $sortedModules as $source => $groups ) {
419 foreach ( $groups as $group => $grpModules ) {
420 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
422 if ( $group === 'private' ) {
423 // Decide whether to use style or script element
424 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
425 $chunks[] = Html
::inlineStyle(
426 $rl->makeModuleResponse( $context, $grpModules )
429 $chunks[] = ResourceLoader
::makeInlineScript(
430 $rl->makeModuleResponse( $context, $grpModules )
436 // See if we have one or more raw modules
438 foreach ( $grpModules as $key => $module ) {
439 $isRaw |
= $module->isRaw();
442 // Special handling for the user group; because users might change their stuff
443 // on-wiki like user pages, or user preferences; we need to find the highest
444 // timestamp of these user-changeable modules so we can ensure cache misses on change
445 // This should NOT be done for the site group (bug 27564) because anons get that too
446 // and we shouldn't be putting timestamps in CDN-cached HTML
447 if ( $group === 'user' ) {
448 $version = $rl->getCombinedVersion( $context, array_keys( $grpModules ) );
449 $context->setVersion( $version );
452 $context->setModules( array_keys( $grpModules ) );
453 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
455 // Decide whether to use 'style' or 'script' element
456 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
457 $chunk = Html
::linkedStyle( $url );
459 if ( $context->getRaw() ||
$isRaw ) {
460 $chunk = Html
::element( 'script', [
461 // In SpecialJavaScriptTest, QUnit must load synchronous
462 'async' => !isset( $extraQuery['sync'] ),
466 $chunk = ResourceLoader
::makeInlineScript(
467 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
472 if ( $group == 'noscript' ) {
473 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
480 return new WrappedStringList( "\n", $chunks );