Debian Codegraph @

includes/ResourceLoader/CodexModule.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\ResourceLoader;
22
23 use InvalidArgumentException;
24 use MediaWiki\Config\Config;
25 use MediaWiki\Html\Html;
26 use MediaWiki\Html\HtmlJsCode;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\Registration\ExtensionRegistry;
29 use RuntimeException;
30
31 /**
32 * Module for codex that has direction-specific style files and a static helper
33 * function for embedding icons in package modules. This module also contains
34 * logic to support code-splitting (aka tree-shaking) of the Codex library to
35 * return only a subset of component JS and/or CSS files.
36 *
37 * @ingroup ResourceLoader
38 * @internal
39 */
40 class CodexModule extends FileModule {
41 protected const CODEX_DEFAULT_LIBRARY_DIR = 'resources/lib/codex';
42 private const CODEX_MODULE_DEPENDENCIES = [ 'vue' ];
43
44 /** @var array<string,string>|null */
45 private static ?array $themeMap = null;
46
47 /**
48 * Cache for getCodexFiles(). Maps manifest file paths to outputs. For more information about
49 * the structure of the outputs, see the documentation comment for getCodexFiles().
50 *
51 * This array looks like:
52 * [
53 * '/path/to/manifest.json' => [ 'files' => [ ... ], 'components' => [ ... ] ],
54 * '/path/to/manifest-rtl.json' => [ 'files' => [ ... ], 'components' => [ ... ] ],
55 * ...
56 * ]
57 *
58 * @var array<string,array{files:array<string,array{styles:string[],dependencies:string[]}>,components:array<string,string>}>
59 */
60 private static array $codexFilesCache = [];
61
62 /**
63 * Names of the requested components. Comes directly from the 'codexComponents' property in the
64 * module definition.
65 *
66 * @var string[]
67 */
68 private array $codexComponents = [];
69
70 private bool $isStyleOnly = false;
71 private bool $isScriptOnly = false;
72 private bool $codexFullLibrary = false;
73 private bool $setupComplete = false;
74
75 /**
76 * @param array $options [optional]
77 * - codexComponents: array of Codex components to include
78 * - codexFullLibrary: whether to load the entire Codex library
79 * - codexStyleOnly: whether to include only style files
80 * - codexScriptOnly: whether to include only script files
81 * @param string|null $localBasePath [optional]
82 * @param string|null $remoteBasePath [optional]
83 */
84 public function __construct( array $options = [], $localBasePath = null, $remoteBasePath = null ) {
85 if ( isset( $options[ 'codexComponents' ] ) ) {
86 if ( !is_array( $options[ 'codexComponents' ] ) || count( $options[ 'codexComponents' ] ) === 0 ) {
87 throw new InvalidArgumentException(
88 "All 'codexComponents' properties in your module definition file " .
89 'must either be omitted or be an array with at least one component name'
90 );
91 }
92
93 $this->codexComponents = $options[ 'codexComponents' ];
94 }
95
96 if ( isset( $options['codexFullLibrary'] ) ) {
97 if ( isset( $options[ 'codexComponents' ] ) ) {
98 throw new InvalidArgumentException(
99 'ResourceLoader modules using the CodexModule class cannot ' .
100 "use both 'codexFullLibrary' and 'codexComponents' options. " .
101 "Instead, use 'codexFullLibrary' to load the entire library" .
102 "or 'codexComponents' to load a subset of components."
103 );
104 }
105
106 $this->codexFullLibrary = $options[ 'codexFullLibrary' ];
107 }
108
109 if ( isset( $options[ 'codexStyleOnly' ] ) ) {
110 $this->isStyleOnly = $options[ 'codexStyleOnly' ];
111 }
112
113 if ( isset( $options[ 'codexScriptOnly' ] ) ) {
114 $this->isScriptOnly = $options[ 'codexScriptOnly' ];
115 }
116
117 // Normalize $options[ 'dependencies' ] to always make it an array. It could be unset, or
118 // it could be a string.
119 $options[ 'dependencies' ] = (array)( $options[ 'dependencies' ] ?? [] );
120
121 // Unlike when the entire @wikimedia/codex module is depended on, when the codexComponents
122 // option is used, Vue is not automatically included, though it is required. Add it and
123 // other dependencies here.
124 if ( !$this->isStyleOnly && count( $this->codexComponents ) > 0 ) {
125 $options[ 'dependencies' ] = array_unique( array_merge(
126 $options[ 'dependencies' ],
127 self::CODEX_MODULE_DEPENDENCIES
128 ) );
129 }
130
131 if ( in_array( '@wikimedia/codex', $options[ 'dependencies' ] ) ) {
132 throw new InvalidArgumentException(
133 'ResourceLoader modules using the CodexModule class cannot ' .
134 "list the '@wikimedia/codex' module as a dependency. " .
135 "Instead, use 'codexComponents' to require a subset of components."
136 );
137 }
138
139 parent::__construct( $options, $localBasePath, $remoteBasePath );
140 }
141
142 /**
143 * Retrieve the specified icon definitions from codex-icons.json. Intended as a convenience
144 * function to be used in packageFiles definitions.
145 *
146 * Example:
147 * "packageFiles": [
148 * {
149 * "name": "icons.json",
150 * "callback": "MediaWiki\\ResourceLoader\\CodexModule::getIcons",
151 * "callbackParam": [
152 * "cdxIconClear",
153 * "cdxIconTrash"
154 * ]
155 * }
156 * ]
157 *
158 * @param Context $context
159 * @param Config $config
160 * @param string[] $iconNames Names of icons to fetch
161 * @return array
162 */
163 public static function getIcons( Context $context, Config $config, array $iconNames = [] ): array {
164 static $cachedIcons = null;
165 static $cachedIconFilePath = null;
166
167 $iconFile = self::getIconFilePath( $config );
168 if ( $cachedIcons === null || $cachedIconFilePath !== $iconFile ) {
169 $cachedIcons = json_decode( file_get_contents( $iconFile ), true );
170 $cachedIconFilePath = $iconFile;
171 }
172
173 return array_intersect_key( $cachedIcons, array_flip( $iconNames ) );
174 }
175
176 private static function getIconFilePath( Config $config ) {
177 $devDir = $config->get( MainConfigNames::CodexDevelopmentDir );
178 $iconsDir = $devDir !== null ?
179 "$devDir/packages/codex-icons/dist" :
180 MW_INSTALL_PATH . '/resources/lib/codex-icons';
181 return "$iconsDir/codex-icons.json";
182 }
183
184 public function getMessages() {
185 $messages = parent::getMessages();
186
187 // Add messages used inside Codex Vue components. The message keys are defined in the
188 // "messageKeys.json" file from the Codex package
189 if ( $this->codexFullLibrary || ( !$this->isStyleOnly && count( $this->codexComponents ) > 0 ) ) {
190 $messageKeyFilePath = $this->makeFilePath( 'messageKeys.json' )->getLocalPath();
191 $messageKeys = json_decode( file_get_contents( $messageKeyFilePath ), true );
192 $messages = array_merge( $messages, $messageKeys );
193 }
194
195 return $messages;
196 }
197
198 // These 3 public methods are the entry points to this class; depending on the
199 // circumstances any one of these might be called first.
200
201 public function getPackageFiles( Context $context ) {
202 $this->setupCodex( $context );
203 return parent::getPackageFiles( $context );
204 }
205
206 public function getStyleFiles( Context $context ) {
207 $this->setupCodex( $context );
208 return parent::getStyleFiles( $context );
209 }
210
211 protected function processStyle( $style, $styleLang, $path, Context $context ) {
212 $pathAsString = $path instanceof FilePath ? $path->getLocalPath() : $path;
213 if ( str_starts_with( $pathAsString, $this->getCodexDirectory() ) ) {
214 // This is a Codex style file, don't do any processing.
215 // We need to avoid CSSJanus flipping in particular, because we're using RTL-specific
216 // files instead. Note that we're bypassing all of processStyle() when we really just
217 // care about bypassing flipping; that's fine for now, but could be a problem if
218 // processStyle() is ever expanded to do more than Less compilation, RTL flipping and
219 // image URL remapping.
220 return $style;
221 }
222
223 return parent::processStyle( $style, $styleLang, $path, $context );
224 }
225
226 public function getDefinitionSummary( Context $context ) {
227 $this->setupCodex( $context );
228 return parent::getDefinitionSummary( $context );
229 }
230
231 public function supportsURLLoading() {
232 // We need to override this explicitly. The parent method might return true if there are
233 // no 'packageFiles' set in the module definition and they're all generated by us.
234 // It's possible that this "should" return true in some circumstances (e.g. style-only use
235 // of CodexModule combined with non-packageFiles scripts), but those are edge cases that
236 // we're choosing not to support here.
237 return false;
238 }
239
240 /**
241 * Get the theme to use based on the current skin.
242 *
243 * @param Context $context
244 * @return string Name of the current theme
245 */
246 private function getTheme( Context $context ): string {
247 if ( self::$themeMap === null ) {
248 // Initialize self::$themeMap
249 $skinCodexThemes = ExtensionRegistry::getInstance()->getAttribute( 'SkinCodexThemes' );
250 self::$themeMap = [ 'default' => 'wikimedia-ui' ] + $skinCodexThemes;
251 }
252 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
253 return self::$themeMap[ $context->getSkin() ] ?? self::$themeMap[ 'default' ];
254 }
255
256 /**
257 * Build a FilePath object representing the path to a Codex file.
258 *
259 * If $wgCodexDevelopmentDir is set, the returned FilePath object points to
260 * $wgCodexDevelopmentDir/$file. Otherwise, it points to resources/lib/codex/$file.
261 *
262 * @param string $file File name
263 */
264 private function makeFilePath( string $file ): FilePath {
265 $remoteBasePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );
266 $devDir = $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir );
267 if ( $devDir === null ) {
268 $filePath = new FilePath(
269 static::CODEX_DEFAULT_LIBRARY_DIR . '/' . $file,
270 MW_INSTALL_PATH,
271 $remoteBasePath
272 );
273 if ( !file_exists( $filePath->getLocalPath() ) ) {
274 throw new RuntimeException( "Could not find Codex file `{$filePath->getLocalPath()}`" );
275 }
276 return $filePath;
277 }
278
279 $modulesDir = $devDir . '/packages/codex/dist/modules';
280 if ( !file_exists( $modulesDir ) ) {
281 throw new RuntimeException(
282 "Could not find Codex development build, `$modulesDir` does not exist. " .
283 "You may need to run `npm run build-all` in the `$devDir` directory, " .
284 "or disable Codex development mode by setting \$wgCodexDevelopmentDir = null;"
285 );
286 }
287 $path = $devDir . '/packages/codex/dist/' . $file;
288 if ( !file_exists( $path ) ) {
289 throw new RuntimeException(
290 "Could not find Codex file `$path`. " .
291 "You may need to run `npm run build-all` in the `$devDir` directory, " .
292 "or you may be using a version of Codex that is too old for this version of MediaWiki."
293 );
294 }
295
296 // Return a modified FilePath object that bypasses LocalBasePath
297 // HACK: We do have to set LocalBasePath to a non-null value, otherwise
298 // FileModule::getLocalPath() will still prepend its own base path
299 return new class ( $path, '' ) extends FilePath {
300 public function getLocalPath(): string {
301 return $this->getPath();
302 }
303 };
304 }
305
306 /**
307 * Get the path to the directory that contains the Codex files.
308 *
309 * In production mode this is resources/lib/codex, but in development mode it can be
310 * somewhere else.
311 *
312 * @return string
313 */
314 private function getCodexDirectory() {
315 // Reuse the logic in makeFilePath by passing in an empty path
316 return $this->makeFilePath( '' )->getLocalPath();
317 }
318
319 private function isDevelopmentMode() {
320 return $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir ) !== null;
321 }
322
323 private function getDevelopmentWarning() {
324 return $this->isDevelopmentMode() ?
325 Html::encodeJsCall( 'mw.log.warn', [
326 "You are using a local development version of Codex, which may not match the latest version. " .
327 "To disable this, set \$wgCodexDevelopmentDir = null;"
328 ] ) :
329 '';
330 }
331
332 /**
333 * Decide which manifest file to use, based on the theme and the direction (LTR or RTL).
334 *
335 * @param Context $context
336 * @return string Name of the manifest file to use
337 */
338 private function getManifestFilePath( Context $context ): string {
339 $themeManifestNames = [
340 'wikimedia-ui' => [
341 'ltr' => 'manifest.json',
342 'rtl' => 'manifest-rtl.json',
343 ],
344 'wikimedia-ui-legacy' => [
345 'ltr' => 'manifest.json',
346 'rtl' => 'manifest-rtl.json',
347 ],
348 'experimental' => [
349 'ltr' => 'manifest.json',
350 'rtl' => 'manifest-rtl.json',
351 ]
352 ];
353
354 $theme = $this->getTheme( $context );
355 $direction = $context->getDirection();
356 if ( !isset( $themeManifestNames[ $theme ] ) ) {
357 throw new InvalidArgumentException( "Unknown Codex theme $theme" );
358 }
359 $manifestFile = $themeManifestNames[ $theme ][ $direction ];
360 $manifestFilePath = $this->makeFilePath( "modules/$manifestFile" );
361 return $manifestFilePath->getLocalPath();
362 }
363
364 /**
365 * Get information about all available Codex files.
366 *
367 * This transforms the Codex manifest to a more useful format, and caches it so that different
368 * instances of this class don't each parse the manifest separately.
369 *
370 * The returned data structure contains a 'files' key with dependency information about every
371 * file (both entry point and non-entry point files), and a 'component' key that is an array
372 * mapping component names to file names. The full data structure looks like this:
373 *
374 * [
375 * 'files' => [
376 * 'CdxButtonGroup.js' => [
377 * 'styles' => [ 'CdxButtonGroup.css' ],
378 * 'dependencies' => [ 'CdxButton.js', 'buttonHelpers.js' ]
379 * ],
380 * // all files are listed here, both entry point and non-entry point files
381 * ],
382 * 'components' => [
383 * 'CdxButtonGroup' => 'CdxButtonGroup.js',
384 * // only entry point files are listed here
385 * ]
386 * ]
387 *
388 * @param Context $context
389 * @return array{files:array<string,array{styles:string[],dependencies:string[]}>,components:array<string,string>}
390 */
391 private function getCodexFiles( Context $context ): array {
392 $manifestFilePath = $this->getManifestFilePath( $context );
393
394 if ( isset( self::$codexFilesCache[ $manifestFilePath ] ) ) {
395 return self::$codexFilesCache[ $manifestFilePath ];
396 }
397
398 $manifest = json_decode( file_get_contents( $manifestFilePath ), true );
399 $files = [];
400 $components = [];
401 foreach ( $manifest as $key => $val ) {
402 $files[ $val[ 'file' ] ] = [
403 'styles' => $val[ 'css' ] ?? [],
404 // $val['imports'] is expressed as manifest keys, transform those to file names
405 'dependencies' => array_map( static function ( $manifestKey ) use ( $manifest ) {
406 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
407 return $manifest[ $manifestKey ][ 'file' ];
408 }, $val[ 'imports' ] ?? [] )
409 ];
410
411 $isComponent = isset( $val[ 'isEntry' ] ) && $val[ 'isEntry' ];
412 if ( $isComponent ) {
413 $fileInfo = pathinfo( $val[ 'file' ] );
414 // $fileInfo[ 'filename' ] is the file name without the extension.
415 // This is the component name (e.g. CdxButton.cjs -> CdxButton).
416 $components[ $fileInfo[ 'filename' ] ] = $val[ 'file' ];
417 }
418 }
419
420 self::$codexFilesCache[ $manifestFilePath ] = [ 'files' => $files, 'components' => $components ];
421 return self::$codexFilesCache[ $manifestFilePath ];
422 }
423
424 /**
425 * There are several different use-cases for CodexModule. We may be dealing
426 * with:
427 *
428 * - A CSS-only or JS & CSS module for the entire component library
429 * - An otherwise standard module that needs one or more Codex icons
430 * - A CSS-only or CSS-and-JS module that has opted-in to Codex's
431 * tree-shaking feature by specifying the "codexComponents" option
432 *
433 * Regardless of the kind of CodexModule we are dealing with, some kind of
434 * one-time setup operation may need to be performed.
435 *
436 * In the case of a full-library module, we need to ensure that the correct
437 * theme- and direction-specific CSS file is used.
438 *
439 * In the case of a tree-shaking module, we need to ensure that the CSS
440 * and/or JS files for the specified components (as well as all
441 * dependencies) are added to the module's packageFiles.
442 *
443 * @param Context $context
444 */
445 private function setupCodex( Context $context ) {
446 if ( $this->setupComplete ) {
447 return;
448 }
449
450 // If we are tree-shaking, add component-specific JS/CSS files
451 if ( count( $this->codexComponents ) > 0 ) {
452 $this->addComponentFiles( $context );
453 }
454
455 // If we want to load the entire Codex library (no tree shaking)
456 if ( $this->codexFullLibrary ) {
457 $this->loadFullCodexLibrary( $context );
458
459 }
460
461 $this->setupComplete = true;
462 }
463
464 /**
465 * Resolve the dependencies for a list of files, return flat arrays of both scripts and styles.
466 * The returned arrays include the files in $requestedFiles, plus their dependencies, their
467 * dependencies' dependencies, etc. The returned arrays are ordered in the order that the files
468 * should be loaded in; in other words, the files are ordered such that each file appears after
469 * all of its dependencies.
470 *
471 * @param string[] $requestedFiles File names whose dependencies to resolve
472 * @phpcs:ignore Generic.Files.LineLength, MediaWiki.Commenting.FunctionComment.MissingParamName
473 * @param array{files:array<string,array{styles:string[],dependencies:string[]}>,components:array<string,string>} $codexFiles
474 * Data structure returned by getCodexFiles()
475 * @return array{scripts:string[],styles:string[]} Resolved dependencies, with script and style
476 * files listed separately.
477 */
478 private function resolveDependencies( array $requestedFiles, array $codexFiles ) {
479 $scripts = [];
480 $styles = [];
481
482 $gatherDependencies = static function ( $file ) use ( &$scripts, &$styles, $codexFiles, &$gatherDependencies ) {
483 foreach ( $codexFiles[ 'files' ][ $file ][ 'dependencies' ] as $dep ) {
484 if ( !in_array( $dep, $scripts ) ) {
485 $gatherDependencies( $dep );
486 }
487 }
488 $scripts[] = $file;
489 $styles = array_merge( $styles, $codexFiles[ 'files' ][ $file ][ 'styles' ] );
490 };
491
492 foreach ( $requestedFiles as $requestedFile ) {
493 $gatherDependencies( $requestedFile );
494 }
495
496 return [ 'scripts' => $scripts, 'styles' => $styles ];
497 }
498
499 /**
500 * For Codex modules that rely on tree-shaking, this method determines
501 * which CSS and/or JS files need to be included by consulting the
502 * appropriate manifest file.
503 *
504 * @param Context $context
505 */
506 private function addComponentFiles( Context $context ) {
507 $codexFiles = $this->getCodexFiles( $context );
508
509 $requestedFiles = array_map( static function ( $component ) use ( $codexFiles ) {
510 if ( !isset( $codexFiles[ 'components' ][ $component ] ) ) {
511 throw new InvalidArgumentException(
512 "\"$component\" is not an export of Codex and cannot be included in the \"codexComponents\" array."
513 );
514 }
515 return $codexFiles[ 'components' ][ $component ];
516 }, $this->codexComponents );
517
518 [ 'scripts' => $scripts, 'styles' => $styles ] = $this->resolveDependencies( $requestedFiles, $codexFiles );
519
520 // Add the CSS files to the module's package file (unless this is a script-only module)
521 if ( !$this->isScriptOnly ) {
522 foreach ( $styles as $fileName ) {
523 $this->styles[] = $this->makeFilePath( "modules/$fileName" );
524 }
525 }
526
527 // Add the JS files to the module's package file (unless this is a style-only module).
528 if ( !$this->isStyleOnly ) {
529 // Add a synthetic top-level "exports" file
530 $exports = [];
531 foreach ( $this->codexComponents as $component ) {
532 $componentFile = $codexFiles[ 'components' ][ $component ];
533 $exports[ $component ] = new HtmlJsCode(
534 'require( ' . Html::encodeJsVar( "./_codex/$componentFile" ) . ' )'
535 );
536 }
537
538 $syntheticExports = Html::encodeJsVar( HtmlJsCode::encodeObject( $exports ) );
539
540 // Add a console warning in development mode
541 $devWarning = $this->getDevelopmentWarning();
542
543 // Proxy the synthetic exports object so that we can throw a useful error if a component
544 // is not defined in the module definition
545 $proxiedSyntheticExports = <<<JAVASCRIPT
546 module.exports = new Proxy( $syntheticExports, {
547 get( target, prop ) {
548 if ( !( prop in target ) ) {
549 throw new Error(
550 `Codex component "\${prop}" ` +
551 'is not listed in the "codexComponents" array ' +
552 'of the "{$this->getName()}" module in your module definition file'
553 );
554 }
555 return target[ prop ];
556 }
557 } );
558 $devWarning
559 JAVASCRIPT;
560
561 $this->packageFiles[] = [
562 'name' => 'codex.js',
563 'content' => $proxiedSyntheticExports
564 ];
565
566 // Add each of the referenced scripts to the package
567 foreach ( $scripts as $fileName ) {
568 $this->packageFiles[] = [
569 'name' => "_codex/$fileName",
570 'file' => $this->makeFilePath( "modules/$fileName" )
571 ];
572 }
573 }
574 }
575
576 /**
577 * For loading the entire Codex library, rather than a subset module of it.
578 *
579 * @param Context $context
580 */
581 private function loadFullCodexLibrary( Context $context ) {
582 // Add all Codex JS files to the module's package
583 if ( !$this->isStyleOnly ) {
584 $jsFilePath = $this->makeFilePath( 'codex.umd.cjs' );
585
586 // Add a console warning in development mode
587 $devWarning = $this->getDevelopmentWarning();
588 if ( $devWarning ) {
589 $this->packageFiles[] = [
590 'name' => 'codex.js',
591 'callback' => static function () use ( $jsFilePath, $devWarning ) {
592 return $devWarning . ';' . file_get_contents( $jsFilePath->getLocalPath() );
593 },
594 'versionCallback' => static function () use ( $jsFilePath ) {
595 return $jsFilePath;
596 }
597 ];
598 } else {
599 $this->packageFiles[] = [
600 'name' => 'codex.js',
601 'file' => $jsFilePath
602 ];
603 }
604 }
605
606 // Add all Codex CSS files to the module's package
607 if ( !$this->isScriptOnly ) {
608 // Theme-specific + direction style files
609 $themeStyles = [
610 'wikimedia-ui' => [
611 'ltr' => 'codex.style.css',
612 'rtl' => 'codex.style-rtl.css'
613 ],
614 'wikimedia-ui-legacy' => [
615 'ltr' => 'codex.style.css',
616 'rtl' => 'codex.style-rtl.css'
617 ],
618 'experimental' => [
619 'ltr' => 'codex.style.css',
620 'rtl' => 'codex.style-rtl.css'
621 ]
622 ];
623
624 $theme = $this->getTheme( $context );
625 $direction = $context->getDirection();
626 $styleFile = $themeStyles[ $theme ][ $direction ];
627 $this->styles[] = $this->makeFilePath( $styleFile );
628 }
629 }
630
631 /**
632 * @inheritDoc
633 */
634 public function getType(): string {
635 return $this->isStyleOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
636 }
637 }