Merge "Update documentation for MediaHandler::getPageDimensions()"
[mediawiki.git] / resources / mediawiki / mediawiki.inspect.js
blobd93254b03ae127a92ea34ef2f41ca584e1da789a
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, $ ) {
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         }
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         }
24         /**
25          * @class mw.inspect
26          * @singleton
27          */
28         var inspect = {
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 = {};
39                         $.each( modules, function ( moduleIndex, moduleName ) {
40                                 var dependencies = mw.loader.moduleRegistry[moduleName].dependencies || [];
42                                 graph[moduleName] = graph[moduleName] || { requiredBy: [] };
43                                 graph[moduleName].requires = dependencies;
45                                 $.each( dependencies, function ( depIndex, depName ) {
46                                         graph[depName] = graph[depName] || { requiredBy: [] };
47                                         graph[depName].requiredBy.push( moduleName );
48                                 } );
49                         } );
50                         return graph;
51                 },
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;
63                         if ( mw.loader.getState( moduleName ) !== 'ready' ) {
64                                 return null;
65                         }
67                         if ( !module.style && !module.script ) {
68                                 return null;
69                         }
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                         }
78                         // Tally JavaScript
79                         if ( $.isFunction( module.script ) ) {
80                                 payload += $.byteLength( module.script.toString() );
81                         }
83                         return payload;
84                 },
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;
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                 },
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                 },
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( $.toJSON( data, null, 2 ) );
146                                 return;
147                         } catch (e) {}
148                         mw.log( data );
149                 },
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; } );
163                         $.each( reports, function ( index, name ) {
164                                 inspect.dumpTable( inspect.reports[name]() );
165                         } );
166                 },
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                                 } );
186                                 // Sort module descriptors by size, largest first.
187                                 sortByProperty( modules, 'size', true );
189                                 // Convert size to human-readable string.
190                                 $.each( modules, function ( i, module ) {
191                                         module.size = humanSize( module.size );
192                                 } );
194                                 return modules;
195                         },
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 = [];
204                                 $.each( inspect.getLoadedModules(), function ( index, name ) {
205                                         var css, stats, module = mw.loader.moduleRegistry[name];
207                                         try {
208                                                 css = module.style.css.join();
209                                         } catch (e) { return; } // skip
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                         },
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         };
243         if ( mw.config.get( 'debug' ) ) {
244                 mw.log( 'mw.inspect: reports are not available in debug mode.' );
245         }
247         mw.inspect = inspect;
249 }( mediaWiki, jQuery ) );