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 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 $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
138 // Embedding for private modules
146 foreach ( $this->modules
as $name ) {
147 $module = $rl->getModule( $name );
152 $group = $module->getGroup();
154 if ( $group === 'private' ) {
155 // Embed via mw.loader.implement per T36907.
156 $data['embed']['general'][] = $name;
157 // Avoid duplicate request from mw.loader
158 $data['states'][$name] = 'loading';
160 // Load via mw.loader.load()
161 $data['general'][] = $name;
165 foreach ( $this->moduleStyles
as $name ) {
166 $module = $rl->getModule( $name );
171 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
172 $logger = $rl->getLogger();
173 $logger->debug( 'Unexpected general module "{module}" in styles queue.', [
177 // Stylesheet doesn't trigger mw.loader callback.
178 // Set "ready" state to allow dependencies and avoid duplicate requests. (T87871)
179 $data['states'][$name] = 'ready';
182 $group = $module->getGroup();
183 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
184 if ( $module->isKnownEmpty( $context ) ) {
185 // Avoid needless request for empty module
186 $data['states'][$name] = 'ready';
188 if ( $group === 'private' ) {
189 // Embed via style element
190 $data['embed']['styles'][] = $name;
191 // Avoid duplicate request from mw.loader
192 $data['states'][$name] = 'ready';
194 // Load from load.php?only=styles via <link rel=stylesheet>
195 $data['styles'][] = $name;
200 foreach ( $this->moduleScripts
as $name ) {
201 $module = $rl->getModule( $name );
206 $group = $module->getGroup();
207 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
208 if ( $module->isKnownEmpty( $context ) ) {
209 // Avoid needless request for empty module
210 $data['states'][$name] = 'ready';
212 // Load from load.php?only=scripts via <script src></script>
213 $data['scripts'][] = $name;
215 // Avoid duplicate request from mw.loader
216 $data['states'][$name] = 'loading';
224 * @return array Attribute key-value pairs for the HTML document element
226 public function getDocumentAttributes() {
227 return [ 'class' => 'client-nojs' ];
231 * The order of elements in the head is as follows:
234 * - Async external script-src.
237 * - Script execution may be blocked on preceeding stylesheets.
238 * - Async scripts are not blocked on stylesheets.
239 * - Inline scripts can't be asynchronous.
240 * - For styles, earlier is better.
242 * @return string|WrappedStringList HTML
244 public function getHeadHtml() {
245 $data = $this->getData();
248 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
249 // This happens synchronously on every page view to avoid flashes of wrong content.
250 // See also #getDocumentAttributes() and /resources/src/startup.js.
251 $chunks[] = Html
::inlineScript(
252 'document.documentElement.className = document.documentElement.className'
253 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
256 // Inline RLQ: Set page variables
257 if ( $this->config
) {
258 $chunks[] = ResourceLoader
::makeInlineScript(
259 ResourceLoader
::makeConfigSetScript( $this->config
)
263 // Inline RLQ: Initial module states
264 $states = array_merge( $this->exemptStates
, $data['states'] );
266 $chunks[] = ResourceLoader
::makeInlineScript(
267 ResourceLoader
::makeLoaderStateScript( $states )
271 // Inline RLQ: Embedded modules
272 if ( $data['embed']['general'] ) {
273 $chunks[] = $this->getLoad(
274 $data['embed']['general'],
275 ResourceLoaderModule
::TYPE_COMBINED
279 // Inline RLQ: Load general modules
280 if ( $data['general'] ) {
281 $chunks[] = ResourceLoader
::makeInlineScript(
282 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
286 // Inline RLQ: Load only=scripts
287 if ( $data['scripts'] ) {
288 $chunks[] = $this->getLoad(
290 ResourceLoaderModule
::TYPE_SCRIPTS
294 // External stylesheets
295 if ( $data['styles'] ) {
296 $chunks[] = $this->getLoad(
298 ResourceLoaderModule
::TYPE_STYLES
302 // Inline stylesheets (embedded only=styles)
303 if ( $data['embed']['styles'] ) {
304 $chunks[] = $this->getLoad(
305 $data['embed']['styles'],
306 ResourceLoaderModule
::TYPE_STYLES
310 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
311 // Pass-through a custom target from OutputPage (T143066).
312 $startupQuery = $this->target ?
[ 'target' => $this->target
] : [];
313 $chunks[] = $this->getLoad(
315 ResourceLoaderModule
::TYPE_SCRIPTS
,
319 return WrappedStringList
::join( "\n", $chunks );
323 * @return string|WrappedStringList HTML
325 public function getBodyHtml() {
329 private function getContext( $group, $type ) {
330 return self
::makeContext( $this->context
, $group, $type );
333 private function getLoad( $modules, $only, array $extraQuery = [] ) {
334 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery );
337 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
338 array $extraQuery = []
340 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
341 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
342 // Set 'only' if not combined
343 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
344 // Remove user parameter in most cases
345 if ( $group !== 'user' && $group !== 'private' ) {
346 $req->setVal( 'user', null );
348 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
349 // Allow caller to setVersion() and setModules()
350 return new DerivativeResourceLoaderContext( $context );
354 * Explicily load or embed modules on a page.
356 * @param ResourceLoaderContext $mainContext
357 * @param array $modules One or more module names
358 * @param string $only ResourceLoaderModule TYPE_ class constant
359 * @param array $extraQuery [optional] Array with extra query parameters for the request
360 * @return string|WrappedStringList HTML
362 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
363 array $extraQuery = []
365 $rl = $mainContext->getResourceLoader();
368 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
370 // Recursively call us for every item
371 foreach ( $modules as $name ) {
372 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
374 return new WrappedStringList( "\n", $chunks );
377 // Sort module names so requests are more uniform
379 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
381 foreach ( $modules as $name ) {
382 $module = $rl->getModule( $name );
384 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
387 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
390 foreach ( $sortedModules as $source => $groups ) {
391 foreach ( $groups as $group => $grpModules ) {
392 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
393 $context->setModules( array_keys( $grpModules ) );
395 if ( $group === 'private' ) {
396 // Decide whether to use style or script element
397 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
398 $chunks[] = Html
::inlineStyle(
399 $rl->makeModuleResponse( $context, $grpModules )
402 $chunks[] = ResourceLoader
::makeInlineScript(
403 $rl->makeModuleResponse( $context, $grpModules )
409 // See if we have one or more raw modules
411 foreach ( $grpModules as $key => $module ) {
412 $isRaw |
= $module->isRaw();
415 // Special handling for the user group; because users might change their stuff
416 // on-wiki like user pages, or user preferences; we need to find the highest
417 // timestamp of these user-changeable modules so we can ensure cache misses on change
418 // This should NOT be done for the site group (bug 27564) because anons get that too
419 // and we shouldn't be putting timestamps in CDN-cached HTML
420 if ( $group === 'user' ) {
421 // Must setModules() before makeVersionQuery()
422 $context->setVersion( $rl->makeVersionQuery( $context ) );
425 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
427 // Decide whether to use 'style' or 'script' element
428 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
429 $chunk = Html
::linkedStyle( $url );
431 if ( $context->getRaw() ||
$isRaw ) {
432 $chunk = Html
::element( 'script', [
433 // In SpecialJavaScriptTest, QUnit must load synchronous
434 'async' => !isset( $extraQuery['sync'] ),
438 $chunk = ResourceLoader
::makeInlineScript(
439 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
444 if ( $group == 'noscript' ) {
445 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
452 return new WrappedStringList( "\n", $chunks );