<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[27830] trunk/src/wp-admin/js/theme.js: Theme Installer: Caching and paginating of API requests.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://core.trac.wordpress.org/changeset/27830">27830</a></dd>
<dt>Author</dt> <dd>nacin</dd>
<dt>Date</dt> <dd>2014-03-28 21:48:52 +0000 (Fri, 28 Mar 2014)</dd>
</dl>

<h3>Log Message</h3>
<pre>Theme Installer: Caching and paginating of API requests.

props matveb.
see <a href="http://core.trac.wordpress.org/ticket/27055">#27055</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpadminjsthemejs">trunk/src/wp-admin/js/theme.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpadminjsthemejs"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-admin/js/theme.js (27829 => 27830)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-admin/js/theme.js   2014-03-28 21:43:58 UTC (rev 27829)
+++ trunk/src/wp-admin/js/theme.js      2014-03-28 21:48:52 UTC (rev 27830)
</span><span class="lines">@@ -213,6 +213,124 @@
</span><span class="cx">          collection = _( collection.first( 20 ) );
</span><span class="cx"> 
</span><span class="cx">          return collection;
</span><ins>+       },
+
+       // Handles requests for more themes
+       // and caches results
+       //
+       // When we are missing a cache object we fire an apiCall()
+       // which triggers events of `query:success` or `query:fail`
+       query: function( request ) {
+               /**
+                * @static
+                * @type Array
+                */
+               var queries = this.queries,
+                       self = this,
+                       query, isPaginated, count;
+
+               // Search the query cache for matches.
+               query = _.find( queries, function( query ) {
+                       return _.isEqual( query.request, request );
+               });
+
+               // If the request matches the stored currentQuery.request
+               // it means we have a paginated request.
+               isPaginated = _.has( request, 'page' );
+
+               // Reset the internal api page counter for non paginated queries.
+               if ( ! isPaginated ) {
+                       this.currentQuery.page = 1;
+               }
+
+               // Otherwise, send a new API call and add it to the cache.
+               if ( ! query ) {
+                       query = this.apiCall( request ).done( function( data ) {
+                               // Update the collection with the queried data.
+                               self.reset( data.themes );
+                               count = data.info.results;
+
+                               // Trigger a collection refresh event
+                               // and a `query:success` event with a `count` argument.
+                               self.trigger( 'update' );
+                               self.trigger( 'query:success', count );
+
+                               // Store the results and the query request
+                               queries.push( { themes: data.themes, request: request } );
+                       }).fail( function() {
+                               self.trigger( 'query:fail' );
+                       });
+               } else {
+                       // If it's a paginated request we need to fetch more themes...
+                       if ( isPaginated ) {
+                               return this.apiCall( request, isPaginated ).done( function( data ) {
+                                       // Add the new themes to the current collection
+                                       // @todo update counter
+                                       self.add( data.themes );
+                                       self.trigger( 'query:success' );
+
+                               }).fail( function() {
+                                       self.trigger( 'query:fail' );
+                               });
+                       }
+
+                       // Only trigger an update event since we already have the themes
+                       // on our cached object
+                       this.reset( query.themes );
+                       this.trigger( 'update' );
+               }
+       },
+
+       // Local cache array for API queries
+       queries: [],
+
+       // Keep track of current query so we can handle pagination
+       currentQuery: {
+               page: 1,
+               request: {}
+       },
+
+       // Send Ajax POST request to api.wordpress.org/themes
+       apiCall: function( request, paginated ) {
+               // Store current query request args
+               // for later use with the event `theme:end`
+               this.currentQuery.request = request;
+
+               // Ajax request to .org API
+               return $.ajax({
+                       url: 'https://api.wordpress.org/themes/info/1.1/?action=query_themes',
+
+                       // We want JSON data
+                       dataType: 'json',
+                       type: 'POST',
+                       crossDomain: true,
+
+                       // Request data
+                       data: {
+                               action: 'query_themes',
+                               request: _.extend({
+                                       per_page: 72,
+                                       fields: {
+                                               description: true,
+                                               tested: true,
+                                               requires: true,
+                                               rating: true,
+                                               downloaded: true,
+                                               downloadLink: true,
+                                               last_updated: true,
+                                               homepage: true,
+                                               num_ratings: true
+                                       }
+                               }, request)
+                       },
+
+                       beforeSend: function() {
+                               if ( ! paginated ) {
+                                       // Spin it
+                                       $( 'body' ).addClass( 'loading-themes' );
+                               }
+                       }
+               });
</ins><span class="cx">   }
</span><span class="cx"> });
</span><span class="cx"> 
</span><span class="lines">@@ -571,6 +689,15 @@
</span><span class="cx">                  self.render( this );
</span><span class="cx">          });
</span><span class="cx"> 
</span><ins>+               // Update theme count to full result set when available.
+               this.listenTo( self.collection, 'query:success', function( count ) {
+                       if ( _.isNumber( count ) ) {
+                               self.count.text( count );
+                       } else {
+                               self.count.text( self.collection.length );
+                       }
+               });
+
</ins><span class="cx">           this.listenTo( this.parent, 'theme:scroll', function() {
</span><span class="cx">                  self.renderThemes( self.parent.page );
</span><span class="cx">          });
</span><span class="lines">@@ -582,7 +709,7 @@
</span><span class="cx">          } );
</span><span class="cx"> 
</span><span class="cx">          // Bind keyboard events.
</span><del>-               $('body').on( 'keyup', function( event ) {
</del><ins>+                $( 'body' ).on( 'keyup', function( event ) {
</ins><span class="cx">                   if ( ! self.overlay ) {
</span><span class="cx">                          return;
</span><span class="cx">                  }
</span><span class="lines">@@ -628,7 +755,10 @@
</span><span class="cx"> 
</span><span class="cx">          // Generate the themes
</span><span class="cx">          // Using page instance
</span><del>-               this.renderThemes( this.parent.page );
</del><ins>+                // While checking the collection has items
+               if ( this.options.collection.size() > 0 ) {
+                       this.renderThemes( this.parent.page );
+               }
</ins><span class="cx"> 
</span><span class="cx">          // Display a live theme count for the collection
</span><span class="cx">          this.count.text( this.collection.length );
</span><span class="lines">@@ -642,7 +772,9 @@
</span><span class="cx">          self.instance = self.collection.paginate( page );
</span><span class="cx"> 
</span><span class="cx">          // If we have no more themes bail
</span><del>-               if ( self.instance.length === 0 ) {
</del><ins>+                if ( self.instance.size() === 0 ) {
+                       // Fire a no-more-themes event.
+                       this.parent.trigger( 'theme:end' );
</ins><span class="cx">                   return;
</span><span class="cx">          }
</span><span class="cx"> 
</span><span class="lines">@@ -967,7 +1099,7 @@
</span><span class="cx">          _.debounce( _.bind( this.doSearch, this ), 300 )( event.target.value );
</span><span class="cx">  },
</span><span class="cx"> 
</span><del>-       doSearch: function( value ) {
</del><ins>+        doSearch: _.debounce( function( value ) {
</ins><span class="cx">           var request = {},
</span><span class="cx">                  self = this;
</span><span class="cx"> 
</span><span class="lines">@@ -991,23 +1123,10 @@
</span><span class="cx">                  request.tag = [ value.slice( 4 ) ];
</span><span class="cx">          }
</span><span class="cx"> 
</span><del>-               // Send Ajax POST request to api.wordpress.org/themes
-               themes.view.Installer.prototype.apiCall( request ).done( function( data ) {
-                               // Update the collection with the queried data
-                               self.collection.reset( data.themes );
-                               // Trigger a collection refresh event to render the views
-                               self.collection.trigger( 'update' );
-
-                               // Un-spin it
-                               $( 'body' ).removeClass( 'loading-themes' );
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-               }).fail( function() {
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-                               $( '.theme-browser' ).append( '<div class="error"><p>' + l10n.error + '</p></div>' );
-               });
-
-               return false;
-       }
</del><ins>+                // Get the themes by sending Ajax POST request to api.wordpress.org/themes
+               // or searching the local cache
+               this.collection.query( request );
+       }, 300 ),
</ins><span class="cx"> });
</span><span class="cx"> 
</span><span class="cx"> themes.view.Installer = themes.view.Appearance.extend({
</span><span class="lines">@@ -1022,62 +1141,33 @@
</span><span class="cx">          'click [type="checkbox"]': 'addFilter'
</span><span class="cx">  },
</span><span class="cx"> 
</span><del>-       // Send Ajax POST request to api.wordpress.org/themes
-       apiCall: function( request ) {
-               return $.ajax({
-                       url: 'https://api.wordpress.org/themes/info/1.1/?action=query_themes',
-
-                       // We want JSON data
-                       dataType: 'json',
-                       type: 'POST',
-                       crossDomain: true,
-
-                       // Request data
-                       data: {
-                               action: 'query_themes',
-                               request: _.extend({
-                                       per_page: 36,
-                                       fields: {
-                                               description: true,
-                                               tested: true,
-                                               requires: true,
-                                               rating: true,
-                                               downloaded: true,
-                                               downloadLink: true,
-                                               last_updated: true,
-                                               homepage: true,
-                                               num_ratings: true
-                                       }
-                               }, request)
-                       },
-
-                       beforeSend: function() {
-                               // Spin it
-                               $( 'body' ).addClass( 'loading-themes' );
-                       }
-               });
-       },
-
</del><span class="cx">   // Handles all the rendering of the public theme directory
</span><span class="cx">  browse: function( section ) {
</span><span class="cx">          var self = this;
</span><span class="cx"> 
</span><del>-               // @todo Cache the collection after fetching based on the section
</del><span class="cx">           this.collection = new themes.Collection();
</span><span class="cx"> 
</span><del>-               // Create a new collection with the proper theme data
-               // for each section
-               this.apiCall({ browse: section }).done( function( data ) {
-                       // Update the collection with the queried data
-                       self.collection.reset( data.themes );
-                       // Trigger a collection refresh event to render the views
-                       self.collection.trigger( 'update' );
</del><ins>+                // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
+               this.listenTo( this, 'theme:end', function() {
+                       self.collection.currentQuery.page++;
+                       _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
+                       self.collection.query( self.collection.currentQuery.request );
+               });
</ins><span class="cx"> 
</span><del>-                       // Un-spin it
</del><ins>+                this.listenTo( this.collection, 'query:success', function() {
</ins><span class="cx">                   $( 'body' ).removeClass( 'loading-themes' );
</span><span class="cx">                  $( '.theme-browser' ).find( 'div.error' ).remove();
</span><span class="cx">          });
</span><span class="cx"> 
</span><ins>+               this.listenTo( this.collection, 'query:fail', function() {
+                       $( '.theme-browser' ).find( 'div.error' ).remove();
+                       $( '.theme-browser' ).append( '<div class="error"><p>' + l10n.error + '</p></div>' );
+               });
+
+               // Create a new collection with the proper theme data
+               // for each section
+               this.collection.query( { browse: section } );
+
</ins><span class="cx">           if ( this.view ) {
</span><span class="cx">                  this.view.remove();
</span><span class="cx">          }
</span><span class="lines">@@ -1153,27 +1243,12 @@
</span><span class="cx"> 
</span><span class="cx">          // Construct the filter request
</span><span class="cx">          // using the default values
</span><del>-
-               // @todo Cache the collection after fetching based on the filter
</del><span class="cx">           filter = _.union( filter, this.filtersChecked() );
</span><span class="cx">          request = { tag: [ filter ] };
</span><span class="cx"> 
</span><del>-               // Send Ajax POST request to api.wordpress.org/themes
-               this.apiCall( request ).done( function( data ) {
-                               // Update the collection with the queried data
-                               self.collection.reset( data.themes );
-                               // Trigger a collection refresh event to render the views
-                               self.collection.trigger( 'update' );
-
-                               // Un-spin it
-                               $( 'body' ).removeClass( 'loading-themes' );
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-               }).fail( function() {
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-                               $( '.theme-browser' ).append( '<div class="error"><p>' + l10n.error + '</p></div>' );
-               });
-
-               return false;
</del><ins>+                // Get the themes by sending Ajax POST request to api.wordpress.org/themes
+               // or searching the local cache
+               this.collection.query( request );
</ins><span class="cx">   },
</span><span class="cx"> 
</span><span class="cx">  // Clicking on a checkbox triggers a tag request
</span><span class="lines">@@ -1182,20 +1257,9 @@
</span><span class="cx">                  tags = this.filtersChecked(),
</span><span class="cx">                  request = { tag: tags };
</span><span class="cx"> 
</span><del>-               // Send Ajax POST request to api.wordpress.org/themes
-               this.apiCall( request ).done( function( data ) {
-                               // Update the collection with the queried data
-                               self.collection.reset( data.themes );
-                               // Trigger a collection refresh event to render the views
-                               self.collection.trigger( 'update' );
-
-                               // Un-spin it
-                               $( 'body' ).removeClass( 'loading-themes' );
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-               }).fail( function() {
-                               $( '.theme-browser' ).find( 'div.error' ).remove();
-                               $( '.theme-browser' ).append( '<div class="error"><p>' + l10n.error + '</p></div>' );
-               });
</del><ins>+                // Get the themes by sending Ajax POST request to api.wordpress.org/themes
+               // or searching the local cache
+               this.collection.query( request );
</ins><span class="cx">   },
</span><span class="cx"> 
</span><span class="cx">  // Get the checked filters and return an array
</span></span></pre>
</div>
</div>

</body>
</html>