Merge "Use descriptive key for array of in a Special:EditWatchlist line"
[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 /*jshint devel:true */
8 ( function ( mw, $ ) {
9
10 function sortByProperty( array, prop, descending ) {
11 var order = descending ? -1 : 1;
12 return array.sort( function ( a, b ) {
13 return a[prop] > b[prop] ? order : a[prop] < b[prop] ? -order : 0;
14 } );
15 }
16
17 function humanSize( bytes ) {
18 if ( !$.isNumeric( bytes ) || bytes === 0 ) { return bytes; }
19 var i = 0, units = [ '', ' kB', ' MB', ' GB', ' TB', ' PB' ];
20 for ( ; bytes >= 1024; bytes /= 1024 ) { i++; }
21 return bytes.toFixed( 1 ) + units[i];
22 }
23
24 /**
25 * @class mw.inspect
26 * @singleton
27 */
28 var inspect = {
29
30 /**
31 * Return a map of all dependency relationships between loaded modules.
32 *
33 * @return {Object} Maps module names to objects. Each sub-object has
34 * two properties, 'requires' and 'requiredBy'.
35 */
36 getDependencyGraph: function () {
37 var modules = inspect.getLoadedModules(), graph = {};
38
39 $.each( modules, function ( moduleIndex, moduleName ) {
40 var dependencies = mw.loader.moduleRegistry[moduleName].dependencies || [];
41
42 graph[moduleName] = graph[moduleName] || { requiredBy: [] };
43 graph[moduleName].requires = dependencies;
44
45 $.each( dependencies, function ( depIndex, depName ) {
46 graph[depName] = graph[depName] || { requiredBy: [] };
47 graph[depName].requiredBy.push( moduleName );
48 } );
49 } );
50 return graph;
51 },
52
53 /**
54 * Calculate the byte size of a ResourceLoader module.
55 *
56 * @param {string} moduleName The name of the module
57 * @return {number|null} Module size in bytes or null
58 */
59 getModuleSize: function ( moduleName ) {
60 var module = mw.loader.moduleRegistry[ moduleName ],
61 payload = 0;
62
63 if ( mw.loader.getState( moduleName ) !== 'ready' ) {
64 return null;
65 }
66
67 if ( !module.style && !module.script ) {
68 return null;
69 }
70
71 // Tally CSS
72 if ( module.style && $.isArray( module.style.css ) ) {
73 $.each( module.style.css, function ( i, stylesheet ) {
74 payload += $.byteLength( stylesheet );
75 } );
76 }
77
78 // Tally JavaScript
79 if ( $.isFunction( module.script ) ) {
80 payload += $.byteLength( module.script.toString() );
81 }
82
83 return payload;
84 },
85
86 /**
87 * Given CSS source, count both the total number of selectors it
88 * contains and the number which match some element in the current
89 * document.
90 *
91 * @param {string} css CSS source
92 * @return Selector counts
93 * @return {number} return.selectors Total number of selectors
94 * @return {number} return.matched Number of matched selectors
95 */
96 auditSelectors: function ( css ) {
97 var selectors = { total: 0, matched: 0 },
98 style = document.createElement( 'style' ),
99 sheet, rules;
100
101 style.textContent = css;
102 document.body.appendChild( style );
103 // Standards-compliant browsers use .sheet.cssRules, IE8 uses .styleSheet.rules…
104 sheet = style.sheet || style.styleSheet;
105 rules = sheet.cssRules || sheet.rules;
106 $.each( rules, function ( index, rule ) {
107 selectors.total++;
108 if ( document.querySelector( rule.selectorText ) !== null ) {
109 selectors.matched++;
110 }
111 } );
112 document.body.removeChild( style );
113 return selectors;
114 },
115
116 /**
117 * Get a list of all loaded ResourceLoader modules.
118 *
119 * @return {Array} List of module names
120 */
121 getLoadedModules: function () {
122 return $.grep( mw.loader.getModuleNames(), function ( module ) {
123 return mw.loader.getState( module ) === 'ready';
124 } );
125 },
126
127 /**
128 * Print tabular data to the console, using console.table, console.log,
129 * or mw.log (in declining order of preference).
130 *
131 * @param {Array} data Tabular data represented as an array of objects
132 * with common properties.
133 */
134 dumpTable: function ( data ) {
135 try {
136 // Bartosz made me put this here.
137 if ( window.opera ) { throw window.opera; }
138 // Use Function.prototype#call to force an exception on Firefox,
139 // which doesn't define console#table but doesn't complain if you
140 // try to invoke it.
141 console.table.call( console, data );
142 return;
143 } catch ( e ) {}
144 try {
145 console.log( JSON.stringify( data, null, 2 ) );
146 return;
147 } catch ( e ) {}
148 mw.log( data );
149 },
150
151 /**
152 * Generate and print one more reports. When invoked with no arguments,
153 * print all reports.
154 *
155 * @param {string...} [reports] Report names to run, or unset to print
156 * all available reports.
157 */
158 runReports: function () {
159 var reports = arguments.length > 0 ?
160 Array.prototype.slice.call( arguments ) :
161 $.map( inspect.reports, function ( v, k ) { return k; } );
162
163 $.each( reports, function ( index, name ) {
164 inspect.dumpTable( inspect.reports[name]() );
165 } );
166 },
167
168 /**
169 * @class mw.inspect.reports
170 * @singleton
171 */
172 reports: {
173 /**
174 * Generate a breakdown of all loaded modules and their size in
175 * kilobytes. Modules are ordered from largest to smallest.
176 */
177 size: function () {
178 // Map each module to a descriptor object.
179 var modules = $.map( inspect.getLoadedModules(), function ( module ) {
180 return {
181 name: module,
182 size: inspect.getModuleSize( module )
183 };
184 } );
185
186 // Sort module descriptors by size, largest first.
187 sortByProperty( modules, 'size', true );
188
189 // Convert size to human-readable string.
190 $.each( modules, function ( i, module ) {
191 module.size = humanSize( module.size );
192 } );
193
194 return modules;
195 },
196
197 /**
198 * For each module with styles, count the number of selectors, and
199 * count how many match against some element currently in the DOM.
200 */
201 css: function () {
202 var modules = [];
203
204 $.each( inspect.getLoadedModules(), function ( index, name ) {
205 var css, stats, module = mw.loader.moduleRegistry[name];
206
207 try {
208 css = module.style.css.join();
209 } catch ( e ) { return; } // skip
210
211 stats = inspect.auditSelectors( css );
212 modules.push( {
213 module: name,
214 allSelectors: stats.total,
215 matchedSelectors: stats.matched,
216 percentMatched: stats.total !== 0 ?
217 ( stats.matched / stats.total * 100 ).toFixed( 2 ) + '%' : null
218 } );
219 } );
220 sortByProperty( modules, 'allSelectors', true );
221 return modules;
222 },
223
224 /**
225 * Report stats on mw.loader.store: the number of localStorage
226 * cache hits and misses, the number of items purged from the
227 * cache, and the total size of the module blob in localStorage.
228 */
229 store: function () {
230 var raw, stats = { enabled: mw.loader.store.enabled };
231 if ( stats.enabled ) {
232 $.extend( stats, mw.loader.store.stats );
233 try {
234 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
235 stats.totalSize = humanSize( $.byteLength( raw ) );
236 } catch ( e ) {}
237 }
238 return [stats];
239 }
240 },
241
242 /**
243 * Perform a substring search across the JavaScript and CSS source code
244 * of all loaded modules and return an array of the names of the
245 * modules that matched.
246 *
247 * @param {string|RegExp} pattern String or regexp to match.
248 * @return {Array} Array of the names of modules that matched.
249 */
250 grep: function ( pattern ) {
251 if ( typeof pattern.test !== 'function' ) {
252 // Based on Y.Escape.regex from YUI v3.15.0
253 pattern = new RegExp( pattern.replace( /[\-$\^*()+\[\]{}|\\,.?\s]/g, '\\$&' ), 'g' );
254 }
255
256 return $.grep( inspect.getLoadedModules(), function ( moduleName ) {
257 var module = mw.loader.moduleRegistry[moduleName];
258
259 // Grep module's JavaScript
260 if ( $.isFunction( module.script ) && pattern.test( module.script.toString() ) ) {
261 return true;
262 }
263
264 // Grep module's CSS
265 if (
266 $.isPlainObject( module.style ) && $.isArray( module.style.css )
267 && pattern.test( module.style.css.join( '' ) )
268 ) {
269 // Module's CSS source matches
270 return true;
271 }
272
273 return false;
274 } );
275 }
276 };
277
278 if ( mw.config.get( 'debug' ) ) {
279 mw.log( 'mw.inspect: reports are not available in debug mode.' );
280 }
281
282 mw.inspect = inspect;
283
284 }( mediaWiki, jQuery ) );