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 $context = $this->getContext( $module->getGroup(), ResourceLoaderModule
::TYPE_COMBINED
);
152 if ( $module->isKnownEmpty( $context ) ) {
153 // Avoid needless request or embed for empty module
154 $data['states'][$name] = 'ready';
158 if ( $module->shouldEmbedModule( $this->context
) ) {
159 // Embed via mw.loader.implement per T36907.
160 $data['embed']['general'][] = $name;
161 // Avoid duplicate request from mw.loader
162 $data['states'][$name] = 'loading';
164 // Load via mw.loader.load()
165 $data['general'][] = $name;
169 foreach ( $this->moduleStyles
as $name ) {
170 $module = $rl->getModule( $name );
175 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
176 $logger = $rl->getLogger();
177 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
183 // Stylesheet doesn't trigger mw.loader callback.
184 // Set "ready" state to allow script modules to depend on this module (T87871).
185 // And to avoid duplicate requests at run-time from mw.loader.
186 $data['states'][$name] = 'ready';
188 $group = $module->getGroup();
189 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
190 // Avoid needless request for empty module
191 if ( !$module->isKnownEmpty( $context ) ) {
192 if ( $module->shouldEmbedModule( $this->context
) ) {
193 // Embed via style element
194 $data['embed']['styles'][] = $name;
196 // Load from load.php?only=styles via <link rel=stylesheet>
197 $data['styles'][] = $name;
202 foreach ( $this->moduleScripts
as $name ) {
203 $module = $rl->getModule( $name );
208 $group = $module->getGroup();
209 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
210 if ( $module->isKnownEmpty( $context ) ) {
211 // Avoid needless request for empty module
212 $data['states'][$name] = 'ready';
214 // Load from load.php?only=scripts via <script src></script>
215 $data['scripts'][] = $name;
217 // Avoid duplicate request from mw.loader
218 $data['states'][$name] = 'loading';
226 * @return array Attribute key-value pairs for the HTML document element
228 public function getDocumentAttributes() {
229 return [ 'class' => 'client-nojs' ];
233 * The order of elements in the head is as follows:
236 * - Async external script-src.
239 * - Script execution may be blocked on preceeding stylesheets.
240 * - Async scripts are not blocked on stylesheets.
241 * - Inline scripts can't be asynchronous.
242 * - For styles, earlier is better.
244 * @return string|WrappedStringList HTML
246 public function getHeadHtml() {
247 $data = $this->getData();
250 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
251 // This happens synchronously on every page view to avoid flashes of wrong content.
252 // See also #getDocumentAttributes() and /resources/src/startup.js.
253 $chunks[] = Html
::inlineScript(
254 'document.documentElement.className = document.documentElement.className'
255 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
258 // Inline RLQ: Set page variables
259 if ( $this->config
) {
260 $chunks[] = ResourceLoader
::makeInlineScript(
261 ResourceLoader
::makeConfigSetScript( $this->config
)
265 // Inline RLQ: Initial module states
266 $states = array_merge( $this->exemptStates
, $data['states'] );
268 $chunks[] = ResourceLoader
::makeInlineScript(
269 ResourceLoader
::makeLoaderStateScript( $states )
273 // Inline RLQ: Embedded modules
274 if ( $data['embed']['general'] ) {
275 $chunks[] = $this->getLoad(
276 $data['embed']['general'],
277 ResourceLoaderModule
::TYPE_COMBINED
281 // Inline RLQ: Load general modules
282 if ( $data['general'] ) {
283 $chunks[] = ResourceLoader
::makeInlineScript(
284 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
288 // Inline RLQ: Load only=scripts
289 if ( $data['scripts'] ) {
290 $chunks[] = $this->getLoad(
292 ResourceLoaderModule
::TYPE_SCRIPTS
296 // External stylesheets
297 if ( $data['styles'] ) {
298 $chunks[] = $this->getLoad(
300 ResourceLoaderModule
::TYPE_STYLES
304 // Inline stylesheets (embedded only=styles)
305 if ( $data['embed']['styles'] ) {
306 $chunks[] = $this->getLoad(
307 $data['embed']['styles'],
308 ResourceLoaderModule
::TYPE_STYLES
312 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
313 // Pass-through a custom 'target' from OutputPage (T143066).
314 $startupQuery = isset( $this->options
['target'] )
315 ?
[ 'target' => (string)$this->options
['target'] ]
317 $chunks[] = $this->getLoad(
319 ResourceLoaderModule
::TYPE_SCRIPTS
,
323 return WrappedStringList
::join( "\n", $chunks );
327 * @return string|WrappedStringList HTML
329 public function getBodyHtml() {
333 private function getContext( $group, $type ) {
334 return self
::makeContext( $this->context
, $group, $type );
337 private function getLoad( $modules, $only, array $extraQuery = [] ) {
338 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery );
341 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
342 array $extraQuery = []
344 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
345 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
346 // Set 'only' if not combined
347 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
348 // Remove user parameter in most cases
349 if ( $group !== 'user' && $group !== 'private' ) {
350 $req->setVal( 'user', null );
352 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
353 // Allow caller to setVersion() and setModules()
354 return new DerivativeResourceLoaderContext( $context );
358 * Explicily load or embed modules on a page.
360 * @param ResourceLoaderContext $mainContext
361 * @param array $modules One or more module names
362 * @param string $only ResourceLoaderModule TYPE_ class constant
363 * @param array $extraQuery [optional] Array with extra query parameters for the request
364 * @return string|WrappedStringList HTML
366 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
367 array $extraQuery = []
369 $rl = $mainContext->getResourceLoader();
372 // Sort module names so requests are more uniform
375 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
377 // Recursively call us for every item
378 foreach ( $modules as $name ) {
379 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
381 return new WrappedStringList( "\n", $chunks );
384 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
386 foreach ( $modules as $name ) {
387 $module = $rl->getModule( $name );
389 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
392 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
395 foreach ( $sortedModules as $source => $groups ) {
396 foreach ( $groups as $group => $grpModules ) {
397 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
399 // Separate sets of linked and embedded modules while preserving order
402 foreach ( $grpModules as $name => $module ) {
403 $shouldEmbed = $module->shouldEmbedModule( $context );
404 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
405 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
407 $moduleSets[$idx][1][$name] = $module;
410 // Link/embed each set
411 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
412 $context->setModules( array_keys( $moduleSet ) );
414 // Decide whether to use style or script element
415 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
416 $chunks[] = Html
::inlineStyle(
417 $rl->makeModuleResponse( $context, $moduleSet )
420 $chunks[] = ResourceLoader
::makeInlineScript(
421 $rl->makeModuleResponse( $context, $moduleSet )
425 // See if we have one or more raw modules
427 foreach ( $moduleSet as $key => $module ) {
428 $isRaw |
= $module->isRaw();
431 // Special handling for the user group; because users might change their stuff
432 // on-wiki like user pages, or user preferences; we need to find the highest
433 // timestamp of these user-changeable modules so we can ensure cache misses on change
434 // This should NOT be done for the site group (T29564) because anons get that too
435 // and we shouldn't be putting timestamps in CDN-cached HTML
436 if ( $group === 'user' ) {
437 // Must setModules() before makeVersionQuery()
438 $context->setVersion( $rl->makeVersionQuery( $context ) );
441 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
443 // Decide whether to use 'style' or 'script' element
444 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
445 $chunk = Html
::linkedStyle( $url );
447 if ( $context->getRaw() ||
$isRaw ) {
448 $chunk = Html
::element( 'script', [
449 // In SpecialJavaScriptTest, QUnit must load synchronous
450 'async' => !isset( $extraQuery['sync'] ),
454 $chunk = ResourceLoader
::makeInlineScript(
455 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
460 if ( $group == 'noscript' ) {
461 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
470 return new WrappedStringList( "\n", $chunks );