aboutsummaryrefslogtreecommitdiffstats
path: root/includes/ResourceLoader/CodexModule.php
blob: 98c024ced1d20d20f6800c930add4dbda7c23598 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

namespace MediaWiki\ResourceLoader;

use ExtensionRegistry;
use MediaWiki\Config\Config;
use MediaWiki\Html\Html;
use MediaWiki\Html\HtmlJsCode;
use MediaWiki\MainConfigNames;

/**
 * Module for codex that has direction-specific style files and a static helper
 * function for embedding icons in package modules. This module also contains
 * logic to support code-splitting (aka tree-shaking) of the Codex library to
 * return only a subset of component JS and/or CSS files.
 *
 * @ingroup ResourceLoader
 * @internal
 */
class CodexModule extends FileModule {
	private const CODEX_MODULE_DIR = 'resources/lib/codex/modules/';

	/** @var array<string,string> */
	private array $themeMap = [];

	/** @var array<string,array> */
	private array $themeStyles = [];

	/** @var array<string> */
	private array $codexComponents = [];

	private bool $hasThemeStyles = false;
	private bool $isStyleOnly = false;
	private bool $isScriptOnly = false;
	private bool $setupComplete = false;

	public function __construct( array $options = [], $localBasePath = null, $remoteBasePath = null ) {
		$skinCodexThemes = ExtensionRegistry::getInstance()->getAttribute( 'SkinCodexThemes' );
		$this->themeMap = [ 'default' => 'wikimedia-ui' ] + $skinCodexThemes;

		if ( isset( $options['themeStyles'] ) ) {
			$this->hasThemeStyles = true;
			$this->themeStyles = $options[ 'themeStyles' ];
		}

		if ( isset( $options[ 'codexComponents' ] ) ) {
			$this->codexComponents = $options[ 'codexComponents' ];
		}

		if ( isset( $options[ 'codexStyleOnly' ] ) ) {
			$this->isStyleOnly = $options[ 'codexStyleOnly' ];
		}

		if ( isset( $options[ 'codexScriptOnly' ] ) ) {
			$this->isScriptOnly = $options[ 'codexScriptOnly' ];
		}

		parent::__construct( $options, $localBasePath, $remoteBasePath );
	}

	/**
	 * Retrieve the specified icon definitions from codex-icons.json. Intended as a convenience
	 * function to be used in packageFiles definitions.
	 *
	 * Example:
	 *     "packageFiles": [
	 *         {
	 *             "name": "icons.json",
	 *             "callback": "MediaWiki\\ResourceLoader\\CodexModule::getIcons",
	 *             "callbackParam": [
	 *                 "cdxIconClear",
	 *                 "cdxIconTrash"
	 *             ]
	 *         }
	 *     ]
	 *
	 * @param Context $context
	 * @param Config $config
	 * @param string[] $iconNames Names of icons to fetch
	 * @return array
	 */
	public static function getIcons( Context $context, Config $config, array $iconNames = [] ): array {
		global $IP;
		static $allIcons = null;
		if ( $allIcons === null ) {
			$allIcons = json_decode( file_get_contents( "$IP/resources/lib/codex-icons/codex-icons.json" ), true );
		}
		return array_intersect_key( $allIcons, array_flip( $iconNames ) );
	}

	// These 3 public methods are the entry points to this class; depending on the
	// circumstances any one of these might be called first.

	public function getPackageFiles( Context $context ) {
		$this->setupCodex( $context );
		return parent::getPackageFiles( $context );
	}

	public function getStyleFiles( Context $context ) {
		$this->setupCodex( $context );
		return parent::getStyleFiles( $context );
	}

	public function getDefinitionSummary( Context $context ) {
		$this->setupCodex( $context );
		return parent::getDefinitionSummary( $context );
	}

	/**
	 * @param Context $context
	 * @return string Name of the manifest file to use
	 */
	private function getManifestFile( Context $context ): string {
		$isRtl = $context->getDirection() === 'rtl';
		$isLegacy = $this->getTheme( $context ) === 'wikimedia-ui-legacy';
		$manifestFile = null;

		if ( $isRtl && $isLegacy ) {
			$manifestFile = 'manifest-legacy-rtl.json';
		} elseif ( $isRtl ) {
			$manifestFile = 'manifest-rtl.json';
		} elseif ( $isLegacy ) {
			$manifestFile = 'manifest-legacy.json';
		} else {
			$manifestFile = 'manifest.json';
		}

		return $manifestFile;
	}

	/**
	 * @param Context $context
	 * @return string Name of the current theme
	 */
	private function getTheme( Context $context ): string {
		return $this->themeMap[ $context->getSkin() ] ?? $this->themeMap[ 'default' ];
	}

	/**
	 * There are several different use-cases for CodexModule. We may be dealing
	 * with:
	 *
	 * - A CSS-only or JS & CSS module for the entire component library
	 * - An otherwise standard module that needs one or more Codex icons
	 * - A CSS-only or CSS-and-JS module that has opted-in to Codex's
	 *   tree-shaking feature by specifying the "codexComponents" option
	 *
	 * Regardless of the kind of CodexModule we are dealing with, some kind of
	 * one-time setup operation may need to be performed.
	 *
	 * In the case of a full-library module, we need to ensure that the correct
	 * theme- and direction-specific CSS file is used.
	 *
	 * In the case of a tree-shaking module, we need to ensure that the CSS
	 * and/or JS files for the specified components (as well as all
	 * dependencies) are added to the module's packageFiles.
	 *
	 * @param Context $context
	 */
	private function setupCodex( Context $context ) {
		if ( $this->setupComplete ) {
			return;
		}

		// If we are tree-shaking, add component-specific JS/CSS files
		if ( count( $this->codexComponents ) > 0 ) {
			$this->addComponentFiles( $context );
		}

		// If themestyles are present, add them to the module styles
		if ( $this->hasThemeStyles ) {
			$theme = $this->getTheme( $context );
			$dir = $context->getDirection();
			$styles = $this->themeStyles[ $theme ][ $dir ];
			$this->styles = array_merge( $this->styles, (array)$styles );
		}

		$this->setupComplete = true;
	}

	/**
	 * Resolve the dependencies for a list of keys in a given manifest,
	 * and return flat arrays of both scripts and styles. Dependencies
	 * are ordered.
	 *
	 * @param array<string> $keys
	 * @param array<string,array> $manifest
	 * @return array<string,array>
	 */
	private function resolveDependencies( $keys, $manifest ): array {
		$resolvedKeys = [];
		$scripts = [];
		$styles = [];

		$gatherDependencies = static function ( $key ) use ( &$resolvedKeys, $manifest, &$gatherDependencies ) {
			foreach ( $manifest[ $key ][ 'imports' ] ?? [] as $dep ) {
				if ( !in_array( $dep, $resolvedKeys ) ) {
					$gatherDependencies( $dep );
				}
			}
			$resolvedKeys[] = $key;
		};

		foreach ( $keys as $key ) {
			$gatherDependencies( $key );
		}

		foreach ( $resolvedKeys as $key ) {
			$scripts[] = $manifest[ $key ][ 'file' ];
			foreach ( $manifest[ $key ][ 'css'] ?? [] as $css ) {
				$styles[] = $css;
			}
		}

		return [
			'scripts' => $scripts,
			'styles' => $styles
		];
	}

	/**
	 * For Codex modules that rely on tree-shaking, this method determines
	 * which CSS and/or JS files need to be included by consulting the
	 * appropriate manifest file.
	 *
	 * @param Context $context
	 */
	private function addComponentFiles( Context $context ) {
		$remoteBasePath = $this->getConfig()->get( MainConfigNames::ResourceBasePath );

		// Manifest data structure representing all Codex components in the library
		$manifest = json_decode(
			file_get_contents( MW_INSTALL_PATH . '/' . self::CODEX_MODULE_DIR . $this->getManifestFile( $context ) ),
			true
		);

		// Generate an array of manifest keys that meet the following conditions:
		// * Entry has a "file" property that matches one of the specified codexComponents (sans extension)
		// * The "file" property has a ".js" file extension
		$manifestKeys = array_keys( array_filter( $manifest, function ( $val ) {
			$file = pathinfo( $val[ 'file' ] );
			return (
				array_key_exists( 'extension', $file ) &&
				$file[ 'extension' ] === 'js' &&
				in_array( $file[ 'filename' ], $this->codexComponents )
			);
		} ) );

		[ 'scripts' => $scripts, 'styles' => $styles ] = $this->resolveDependencies( $manifestKeys, $manifest );

		// Add the CSS files to the module's package file (unless this is a script-only module)
		if ( !( $this->isScriptOnly ) ) {
			foreach ( $styles as $fileName ) {
				$this->styles[] = new FilePath( self::CODEX_MODULE_DIR . $fileName, MW_INSTALL_PATH, $remoteBasePath );
			}
		}

		// Add the JS files to the module's package file (unless this is a style-only module)
		if ( !( $this->isStyleOnly ) ) {
			$exports = [];
			foreach ( $this->codexComponents as $component ) {
				$exports[ $component ] = new HtmlJsCode(
					'require( ' . Html::encodeJsVar( "./_codex/$component.js" ) . ' )'
				);
			}

			// Add a synthetic top-level "exports" file
			$this->packageFiles[] = [
				'name' => 'codex.js',
				'content' => 'module.exports = ' . Html::encodeJsVar( HtmlJsCode::encodeObject( $exports ) ) . ';'
			];

			// Add each of the referenced scripts to the package
			foreach ( $scripts as $fileName ) {
				$this->packageFiles[] = [
					'name' => "_codex/$fileName",
					'file' => new FilePath( self::CODEX_MODULE_DIR . $fileName, MW_INSTALL_PATH, $remoteBasePath )
				];
			}
		}
	}
}

/** @deprecated since 1.39 */
class_alias( CodexModule::class, 'ResourceLoaderCodexModule' );