Merge "Skin: Make skins aware of their registered skin name"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.inspect.js
1 /*!
2 * Tools for inspecting page composition and performance.
3 *
4 * @author Ori Livneh
5 * @since 1.22
6 */
7
8 /* eslint-disable no-console */
9
10 ( function ( mw, $ ) {
11
12 var inspect,
13 hasOwn = Object.prototype.hasOwnProperty;
14
15 function sortByProperty( array, prop, descending ) {
16 var order = descending ? -1 : 1;
17 return array.sort( function ( a, b ) {
18 return a[ prop ] > b[ prop ] ? order : a[ prop ] < b[ prop ] ? -order : 0;
19 } );
20 }
21
22 function humanSize( bytes ) {
23 var i,
24 units = [ '', ' KiB', ' MiB', ' GiB', ' TiB', ' PiB' ];
25
26 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
27
28 for ( i = 0; bytes >= 1024; bytes /= 1024 ) { i++; }
29 // Maintain one decimal for kB and above, but don't
30 // add ".0" for bytes.
31 return bytes.toFixed( i > 0 ? 1 : 0 ) + units[ i ];
32 }
33
34 /**
35 * @class mw.inspect
36 * @singleton
37 */
38 inspect = {
39
40 /**
41 * Return a map of all dependency relationships between loaded modules.
42 *
43 * @return {Object} Maps module names to objects. Each sub-object has
44 * two properties, 'requires' and 'requiredBy'.
45 */
46 getDependencyGraph: function () {
47 var modules = inspect.getLoadedModules(),
48 graph = {};
49
50 modules.forEach( function ( moduleName ) {
51 var dependencies = mw.loader.moduleRegistry[ moduleName ].dependencies || [];
52
53 if ( !hasOwn.call( graph, moduleName ) ) {
54 graph[ moduleName ] = { requiredBy: [] };
55 }
56 graph[ moduleName ].requires = dependencies;
57
58 $.each( dependencies, function ( depIndex, depName ) {
59 if ( !hasOwn.call( graph, depName ) ) {
60 graph[ depName ] = { requiredBy: [] };
61 }
62 graph[ depName ].requiredBy.push( moduleName );
63 } );
64 } );
65 return graph;
66 },
67
68 /**
69 * Calculate the byte size of a ResourceLoader module.
70 *
71 * @param {string} moduleName The name of the module
72 * @return {number|null} Module size in bytes or null
73 */
74 getModuleSize: function ( moduleName ) {
75 var module = mw.loader.moduleRegistry[ moduleName ],
76 args, i, size;
77
78 if ( module.state !== 'ready' ) {
79 return null;
80 }
81
82 if ( !module.style && !module.script ) {
83 return 0;
84 }
85
86 function getFunctionBody( func ) {
87 return String( func )
88 // To ensure a deterministic result, replace the start of the function
89 // declaration with a fixed string. For example, in Chrome 55, it seems
90 // V8 seemingly-at-random decides to sometimes put a line break between
91 // the opening brace and first statement of the function body. T159751.
92 .replace( /^\s*function\s*\([^)]*\)\s*{\s*/, 'function(){' )
93 .replace( /\s*}\s*$/, '}' );
94 }
95
96 // Based on the load.php response for this module.
97 // For example: `mw.loader.implement("example", function(){}, {"css":[".x{color:red}"]});`
98 // @see mw.loader.store.set().
99 args = [
100 moduleName,
101 module.script,
102 module.style,
103 module.messages,
104 module.templates
105 ];
106 // Trim trailing null or empty object, as load.php would have done.
107 // @see ResourceLoader::makeLoaderImplementScript and ResourceLoader::trimArray.
108 i = args.length;
109 while ( i-- ) {
110 if ( args[ i ] === null || ( $.isPlainObject( args[ i ] ) && $.isEmptyObject( args[ i ] ) ) ) {
111 args.splice( i, 1 );
112 } else {
113 break;
114 }
115 }
116
117 size = 0;
118 for ( i = 0; i < args.length; i++ ) {
119 if ( typeof args[ i ] === 'function' ) {
120 size += $.byteLength( getFunctionBody( args[ i ] ) );
121 } else {
122 size += $.byteLength( JSON.stringify( args[ i ] ) );
123 }
124 }
125
126 return size;
127 },
128
129 /**
130 * Given CSS source, count both the total number of selectors it
131 * contains and the number which match some element in the current
132 * document.
133 *
134 * @param {string} css CSS source
135 * @return {Object} Selector counts
136 * @return {number} return.selectors Total number of selectors
137 * @return {number} return.matched Number of matched selectors
138 */
139 auditSelectors: function ( css ) {
140 var selectors = { total: 0, matched: 0 },
141 style = document.createElement( 'style' );
142
143 style.textContent = css;
144 document.body.appendChild( style );
145 $.each( style.sheet.cssRules, function ( index, rule ) {
146 selectors.total++;
147 // document.querySelector() on prefixed pseudo-elements can throw exceptions
148 // in Firefox and Safari. Ignore these exceptions.
149 // https://bugs.webkit.org/show_bug.cgi?id=149160
150 // https://bugzilla.mozilla.org/show_bug.cgi?id=1204880
151 try {
152 if ( document.querySelector( rule.selectorText ) !== null ) {
153 selectors.matched++;
154 }
155 } catch ( e ) {}
156 } );
157 document.body.removeChild( style );
158 return selectors;
159 },
160
161 /**
162 * Get a list of all loaded ResourceLoader modules.
163 *
164 * @return {Array} List of module names
165 */
166 getLoadedModules: function () {
167 return mw.loader.getModuleNames().filter( function ( module ) {
168 return mw.loader.getState( module ) === 'ready';
169 } );
170 },
171
172 /**
173 * Print tabular data to the console, using console.table, console.log,
174 * or mw.log (in declining order of preference).
175 *
176 * @param {Array} data Tabular data represented as an array of objects
177 * with common properties.
178 */
179 dumpTable: function ( data ) {
180 try {
181 // Bartosz made me put this here.
182 if ( window.opera ) { throw window.opera; }
183 // Use Function.prototype#call to force an exception on Firefox,
184 // which doesn't define console#table but doesn't complain if you
185 // try to invoke it.
186 // eslint-disable-next-line no-useless-call
187 console.table.call( console, data );
188 return;
189 } catch ( e ) {}
190 try {
191 console.log( JSON.stringify( data, null, 2 ) );
192 return;
193 } catch ( e ) {}
194 mw.log( data );
195 },
196
197 /**
198 * Generate and print one more reports. When invoked with no arguments,
199 * print all reports.
200 *
201 * @param {...string} [reports] Report names to run, or unset to print
202 * all available reports.
203 */
204 runReports: function () {
205 var reports = arguments.length > 0 ?
206 Array.prototype.slice.call( arguments ) :
207 $.map( inspect.reports, function ( v, k ) { return k; } );
208
209 reports.forEach( function ( name ) {
210 inspect.dumpTable( inspect.reports[ name ]() );
211 } );
212 },
213
214 /**
215 * @class mw.inspect.reports
216 * @singleton
217 */
218 reports: {
219 /**
220 * Generate a breakdown of all loaded modules and their size in
221 * kilobytes. Modules are ordered from largest to smallest.
222 *
223 * @return {Object[]} Size reports
224 */
225 size: function () {
226 // Map each module to a descriptor object.
227 var modules = inspect.getLoadedModules().map( function ( module ) {
228 return {
229 name: module,
230 size: inspect.getModuleSize( module )
231 };
232 } );
233
234 // Sort module descriptors by size, largest first.
235 sortByProperty( modules, 'size', true );
236
237 // Convert size to human-readable string.
238 modules.forEach( function ( module ) {
239 module.sizeInBytes = module.size;
240 module.size = humanSize( module.size );
241 } );
242
243 return modules;
244 },
245
246 /**
247 * For each module with styles, count the number of selectors, and
248 * count how many match against some element currently in the DOM.
249 *
250 * @return {Object[]} CSS reports
251 */
252 css: function () {
253 var modules = [];
254
255 inspect.getLoadedModules().forEach( function ( name ) {
256 var css, stats, module = mw.loader.moduleRegistry[ name ];
257
258 try {
259 css = module.style.css.join();
260 } catch ( e ) { return; } // skip
261
262 stats = inspect.auditSelectors( css );
263 modules.push( {
264 module: name,
265 allSelectors: stats.total,
266 matchedSelectors: stats.matched,
267 percentMatched: stats.total !== 0 ?
268 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
269 } );
270 } );
271 sortByProperty( modules, 'allSelectors', true );
272 return modules;
273 },
274
275 /**
276 * Report stats on mw.loader.store: the number of localStorage
277 * cache hits and misses, the number of items purged from the
278 * cache, and the total size of the module blob in localStorage.
279 *
280 * @return {Object[]} Store stats
281 */
282 store: function () {
283 var raw, stats = { enabled: mw.loader.store.enabled };
284 if ( stats.enabled ) {
285 $.extend( stats, mw.loader.store.stats );
286 try {
287 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
288 stats.totalSizeInBytes = $.byteLength( raw );
289 stats.totalSize = humanSize( $.byteLength( raw ) );
290 } catch ( e ) {}
291 }
292 return [ stats ];
293 }
294 },
295
296 /**
297 * Perform a string search across the JavaScript and CSS source code
298 * of all loaded modules and return an array of the names of the
299 * modules that matched.
300 *
301 * @param {string|RegExp} pattern String or regexp to match.
302 * @return {Array} Array of the names of modules that matched.
303 */
304 grep: function ( pattern ) {
305 if ( typeof pattern.test !== 'function' ) {
306 pattern = new RegExp( mw.RegExp.escape( pattern ), 'g' );
307 }
308
309 return inspect.getLoadedModules().filter( function ( moduleName ) {
310 var module = mw.loader.moduleRegistry[ moduleName ];
311
312 // Grep module's JavaScript
313 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
314 return true;
315 }
316
317 // Grep module's CSS
318 if (
319 $.isPlainObject( module.style ) && Array.isArray( module.style.css ) &&
320 pattern.test( module.style.css.join( '' ) )
321 ) {
322 // Module's CSS source matches
323 return true;
324 }
325
326 return false;
327 } );
328 }
329 };
330
331 if ( mw.config.get( 'debug' ) ) {
332 mw.log( 'mw.inspect: reports are not available in debug mode.' );
333 }
334
335 mw.inspect = inspect;
336
337 }( mediaWiki, jQuery ) );