[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/js/ -> theme.js (source)

   1  /**
   2   * @output wp-admin/js/theme.js
   3   */
   4  
   5  /* global _wpThemeSettings, confirm, tb_position */
   6  window.wp = window.wp || {};
   7  
   8  ( function($) {
   9  
  10  // Set up our namespace...
  11  var themes, l10n;
  12  themes = wp.themes = wp.themes || {};
  13  
  14  // Store the theme data and settings for organized and quick access.
  15  // themes.data.settings, themes.data.themes, themes.data.l10n.
  16  themes.data = _wpThemeSettings;
  17  l10n = themes.data.l10n;
  18  
  19  // Shortcut for isInstall check.
  20  themes.isInstall = !! themes.data.settings.isInstall;
  21  
  22  // Setup app structure.
  23  _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
  24  
  25  themes.Model = Backbone.Model.extend({
  26      // Adds attributes to the default data coming through the .org themes api.
  27      // Map `id` to `slug` for shared code.
  28      initialize: function() {
  29          var description;
  30  
  31          // If theme is already installed, set an attribute.
  32          if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
  33              this.set({ installed: true });
  34          }
  35  
  36          // Set the attributes.
  37          this.set({
  38              // `slug` is for installation, `id` is for existing.
  39              id: this.get( 'slug' ) || this.get( 'id' )
  40          });
  41  
  42          // Map `section.description` to `description`
  43          // as the API sometimes returns it differently.
  44          if ( this.has( 'sections' ) ) {
  45              description = this.get( 'sections' ).description;
  46              this.set({ description: description });
  47          }
  48      }
  49  });
  50  
  51  // Main view controller for themes.php.
  52  // Unifies and renders all available views.
  53  themes.view.Appearance = wp.Backbone.View.extend({
  54  
  55      el: '#wpbody-content .wrap .theme-browser',
  56  
  57      window: $( window ),
  58      // Pagination instance.
  59      page: 0,
  60  
  61      // Sets up a throttler for binding to 'scroll'.
  62      initialize: function( options ) {
  63          // Scroller checks how far the scroll position is.
  64          _.bindAll( this, 'scroller' );
  65  
  66          this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
  67          // Bind to the scroll event and throttle
  68          // the results from this.scroller.
  69          this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
  70      },
  71  
  72      // Main render control.
  73      render: function() {
  74          // Setup the main theme view
  75          // with the current theme collection.
  76          this.view = new themes.view.Themes({
  77              collection: this.collection,
  78              parent: this
  79          });
  80  
  81          // Render search form.
  82          this.search();
  83  
  84          this.$el.removeClass( 'search-loading' );
  85  
  86          // Render and append.
  87          this.view.render();
  88          this.$el.empty().append( this.view.el ).addClass( 'rendered' );
  89      },
  90  
  91      // Defines search element container.
  92      searchContainer: $( '.search-form' ),
  93  
  94      // Search input and view
  95      // for current theme collection.
  96      search: function() {
  97          var view,
  98              self = this;
  99  
 100          // Don't render the search if there is only one theme.
 101          if ( themes.data.themes.length === 1 ) {
 102              return;
 103          }
 104  
 105          view = new this.SearchView({
 106              collection: self.collection,
 107              parent: this
 108          });
 109          self.SearchView = view;
 110  
 111          // Render and append after screen title.
 112          view.render();
 113          this.searchContainer
 114              .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
 115              .append( view.el )
 116              .on( 'submit', function( event ) {
 117                  event.preventDefault();
 118              });
 119      },
 120  
 121      // Checks when the user gets close to the bottom
 122      // of the mage and triggers a theme:scroll event.
 123      scroller: function() {
 124          var self = this,
 125              bottom, threshold;
 126  
 127          bottom = this.window.scrollTop() + self.window.height();
 128          threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
 129          threshold = Math.round( threshold * 0.9 );
 130  
 131          if ( bottom > threshold ) {
 132              this.trigger( 'theme:scroll' );
 133          }
 134      }
 135  });
 136  
 137  // Set up the Collection for our theme data.
 138  // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
 139  themes.Collection = Backbone.Collection.extend({
 140  
 141      model: themes.Model,
 142  
 143      // Search terms.
 144      terms: '',
 145  
 146      // Controls searching on the current theme collection
 147      // and triggers an update event.
 148      doSearch: function( value ) {
 149  
 150          // Don't do anything if we've already done this search.
 151          // Useful because the Search handler fires multiple times per keystroke.
 152          if ( this.terms === value ) {
 153              return;
 154          }
 155  
 156          // Updates terms with the value passed.
 157          this.terms = value;
 158  
 159          // If we have terms, run a search...
 160          if ( this.terms.length > 0 ) {
 161              this.search( this.terms );
 162          }
 163  
 164          // If search is blank, show all themes.
 165          // Useful for resetting the views when you clean the input.
 166          if ( this.terms === '' ) {
 167              this.reset( themes.data.themes );
 168              $( 'body' ).removeClass( 'no-results' );
 169          }
 170  
 171          // Trigger a 'themes:update' event.
 172          this.trigger( 'themes:update' );
 173      },
 174  
 175      /**
 176       * Performs a search within the collection.
 177       *
 178       * @uses RegExp
 179       */
 180      search: function( term ) {
 181          var match, results, haystack, name, description, author;
 182  
 183          // Start with a full collection.
 184          this.reset( themes.data.themes, { silent: true } );
 185  
 186          // Trim the term.
 187          term = term.trim();
 188  
 189          // Escape the term string for RegExp meta characters.
 190          term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
 191  
 192          // Consider spaces as word delimiters and match the whole string
 193          // so matching terms can be combined.
 194          term = term.replace( / /g, ')(?=.*' );
 195          match = new RegExp( '^(?=.*' + term + ').+', 'i' );
 196  
 197          // Find results.
 198          // _.filter() and .test().
 199          results = this.filter( function( data ) {
 200              name        = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
 201              description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
 202              author      = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
 203  
 204              haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
 205  
 206              if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
 207                  data.set( 'displayAuthor', true );
 208              }
 209  
 210              return match.test( haystack );
 211          });
 212  
 213          if ( results.length === 0 ) {
 214              this.trigger( 'query:empty' );
 215          } else {
 216              $( 'body' ).removeClass( 'no-results' );
 217          }
 218  
 219          this.reset( results );
 220      },
 221  
 222      // Paginates the collection with a helper method
 223      // that slices the collection.
 224      paginate: function( instance ) {
 225          var collection = this;
 226          instance = instance || 0;
 227  
 228          // Themes per instance are set at 20.
 229          collection = _( collection.rest( 20 * instance ) );
 230          collection = _( collection.first( 20 ) );
 231  
 232          return collection;
 233      },
 234  
 235      count: false,
 236  
 237      /*
 238       * Handles requests for more themes and caches results.
 239       *
 240       *
 241       * When we are missing a cache object we fire an apiCall()
 242       * which triggers events of `query:success` or `query:fail`.
 243       */
 244      query: function( request ) {
 245          /**
 246           * @static
 247           * @type Array
 248           */
 249          var queries = this.queries,
 250              self = this,
 251              query, isPaginated, count;
 252  
 253          // Store current query request args
 254          // for later use with the event `theme:end`.
 255          this.currentQuery.request = request;
 256  
 257          // Search the query cache for matches.
 258          query = _.find( queries, function( query ) {
 259              return _.isEqual( query.request, request );
 260          });
 261  
 262          // If the request matches the stored currentQuery.request
 263          // it means we have a paginated request.
 264          isPaginated = _.has( request, 'page' );
 265  
 266          // Reset the internal api page counter for non paginated queries.
 267          if ( ! isPaginated ) {
 268              this.currentQuery.page = 1;
 269          }
 270  
 271          // Otherwise, send a new API call and add it to the cache.
 272          if ( ! query && ! isPaginated ) {
 273              query = this.apiCall( request ).done( function( data ) {
 274  
 275                  // Update the collection with the queried data.
 276                  if ( data.themes ) {
 277                      self.reset( data.themes );
 278                      count = data.info.results;
 279                      // Store the results and the query request.
 280                      queries.push( { themes: data.themes, request: request, total: count } );
 281                  }
 282  
 283                  // Trigger a collection refresh event
 284                  // and a `query:success` event with a `count` argument.
 285                  self.trigger( 'themes:update' );
 286                  self.trigger( 'query:success', count );
 287  
 288                  if ( data.themes && data.themes.length === 0 ) {
 289                      self.trigger( 'query:empty' );
 290                  }
 291  
 292              }).fail( function() {
 293                  self.trigger( 'query:fail' );
 294              });
 295          } else {
 296              // If it's a paginated request we need to fetch more themes...
 297              if ( isPaginated ) {
 298                  return this.apiCall( request, isPaginated ).done( function( data ) {
 299                      // Add the new themes to the current collection.
 300                      // @todo Update counter.
 301                      self.add( data.themes );
 302                      self.trigger( 'query:success' );
 303  
 304                      // We are done loading themes for now.
 305                      self.loadingThemes = false;
 306  
 307                  }).fail( function() {
 308                      self.trigger( 'query:fail' );
 309                  });
 310              }
 311  
 312              if ( query.themes.length === 0 ) {
 313                  self.trigger( 'query:empty' );
 314              } else {
 315                  $( 'body' ).removeClass( 'no-results' );
 316              }
 317  
 318              // Only trigger an update event since we already have the themes
 319              // on our cached object.
 320              if ( _.isNumber( query.total ) ) {
 321                  this.count = query.total;
 322              }
 323  
 324              this.reset( query.themes );
 325              if ( ! query.total ) {
 326                  this.count = this.length;
 327              }
 328  
 329              this.trigger( 'themes:update' );
 330              this.trigger( 'query:success', this.count );
 331          }
 332      },
 333  
 334      // Local cache array for API queries.
 335      queries: [],
 336  
 337      // Keep track of current query so we can handle pagination.
 338      currentQuery: {
 339          page: 1,
 340          request: {}
 341      },
 342  
 343      // Send request to api.wordpress.org/themes.
 344      apiCall: function( request, paginated ) {
 345          return wp.ajax.send( 'query-themes', {
 346              data: {
 347                  // Request data.
 348                  request: _.extend({
 349                      per_page: 100
 350                  }, request)
 351              },
 352  
 353              beforeSend: function() {
 354                  if ( ! paginated ) {
 355                      // Spin it.
 356                      $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
 357                  }
 358              }
 359          });
 360      },
 361  
 362      // Static status controller for when we are loading themes.
 363      loadingThemes: false
 364  });
 365  
 366  // This is the view that controls each theme item
 367  // that will be displayed on the screen.
 368  themes.view.Theme = wp.Backbone.View.extend({
 369  
 370      // Wrap theme data on a div.theme element.
 371      className: 'theme',
 372  
 373      // Reflects which theme view we have.
 374      // 'grid' (default) or 'detail'.
 375      state: 'grid',
 376  
 377      // The HTML template for each element to be rendered.
 378      html: themes.template( 'theme' ),
 379  
 380      events: {
 381          'click': themes.isInstall ? 'preview': 'expand',
 382          'keydown': themes.isInstall ? 'preview': 'expand',
 383          'touchend': themes.isInstall ? 'preview': 'expand',
 384          'keyup': 'addFocus',
 385          'touchmove': 'preventExpand',
 386          'click .theme-install': 'installTheme',
 387          'click .update-message': 'updateTheme'
 388      },
 389  
 390      touchDrag: false,
 391  
 392      initialize: function() {
 393          this.model.on( 'change', this.render, this );
 394      },
 395  
 396      render: function() {
 397          var data = this.model.toJSON();
 398  
 399          // Render themes using the html template.
 400          this.$el.html( this.html( data ) ).attr({
 401              tabindex: 0,
 402              'aria-describedby' : data.id + '-action ' + data.id + '-name',
 403              'data-slug': data.id
 404          });
 405  
 406          // Renders active theme styles.
 407          this.activeTheme();
 408  
 409          if ( this.model.get( 'displayAuthor' ) ) {
 410              this.$el.addClass( 'display-author' );
 411          }
 412      },
 413  
 414      // Adds a class to the currently active theme
 415      // and to the overlay in detailed view mode.
 416      activeTheme: function() {
 417          if ( this.model.get( 'active' ) ) {
 418              this.$el.addClass( 'active' );
 419          }
 420      },
 421  
 422      // Add class of focus to the theme we are focused on.
 423      addFocus: function() {
 424          var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
 425  
 426          $('.theme.focus').removeClass('focus');
 427          $themeToFocus.addClass('focus');
 428      },
 429  
 430      // Single theme overlay screen.
 431      // It's shown when clicking a theme.
 432      expand: function( event ) {
 433          var self = this;
 434  
 435          event = event || window.event;
 436  
 437          // 'Enter' and 'Space' keys expand the details view when a theme is :focused.
 438          if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
 439              return;
 440          }
 441  
 442          // Bail if the user scrolled on a touch device.
 443          if ( this.touchDrag === true ) {
 444              return this.touchDrag = false;
 445          }
 446  
 447          // Prevent the modal from showing when the user clicks
 448          // one of the direct action buttons.
 449          if ( $( event.target ).is( '.theme-actions a' ) ) {
 450              return;
 451          }
 452  
 453          // Prevent the modal from showing when the user clicks one of the direct action buttons.
 454          if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) {
 455              return;
 456          }
 457  
 458          // Set focused theme to current element.
 459          themes.focusedTheme = this.$el;
 460  
 461          this.trigger( 'theme:expand', self.model.cid );
 462      },
 463  
 464      preventExpand: function() {
 465          this.touchDrag = true;
 466      },
 467  
 468      preview: function( event ) {
 469          var self = this,
 470              current, preview;
 471  
 472          event = event || window.event;
 473  
 474          // Bail if the user scrolled on a touch device.
 475          if ( this.touchDrag === true ) {
 476              return this.touchDrag = false;
 477          }
 478  
 479          // Allow direct link path to installing a theme.
 480          if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) {
 481              return;
 482          }
 483  
 484          // 'Enter' and 'Space' keys expand the details view when a theme is :focused.
 485          if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
 486              return;
 487          }
 488  
 489          // Pressing Enter while focused on the buttons shouldn't open the preview.
 490          if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
 491              return;
 492          }
 493  
 494          event.preventDefault();
 495  
 496          event = event || window.event;
 497  
 498          // Set focus to current theme.
 499          themes.focusedTheme = this.$el;
 500  
 501          // Construct a new Preview view.
 502          themes.preview = preview = new themes.view.Preview({
 503              model: this.model
 504          });
 505  
 506          // Render the view and append it.
 507          preview.render();
 508          this.setNavButtonsState();
 509  
 510          // Hide previous/next navigation if there is only one theme.
 511          if ( this.model.collection.length === 1 ) {
 512              preview.$el.addClass( 'no-navigation' );
 513          } else {
 514              preview.$el.removeClass( 'no-navigation' );
 515          }
 516  
 517          // Append preview.
 518          $( 'div.wrap' ).append( preview.el );
 519  
 520          // Listen to our preview object
 521          // for `theme:next` and `theme:previous` events.
 522          this.listenTo( preview, 'theme:next', function() {
 523  
 524              // Keep local track of current theme model.
 525              current = self.model;
 526  
 527              // If we have ventured away from current model update the current model position.
 528              if ( ! _.isUndefined( self.current ) ) {
 529                  current = self.current;
 530              }
 531  
 532              // Get next theme model.
 533              self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
 534  
 535              // If we have no more themes, bail.
 536              if ( _.isUndefined( self.current ) ) {
 537                  self.options.parent.parent.trigger( 'theme:end' );
 538                  return self.current = current;
 539              }
 540  
 541              preview.model = self.current;
 542  
 543              // Render and append.
 544              preview.render();
 545              this.setNavButtonsState();
 546              $( '.next-theme' ).focus();
 547          })
 548          .listenTo( preview, 'theme:previous', function() {
 549  
 550              // Keep track of current theme model.
 551              current = self.model;
 552  
 553              // Bail early if we are at the beginning of the collection.
 554              if ( self.model.collection.indexOf( self.current ) === 0 ) {
 555                  return;
 556              }
 557  
 558              // If we have ventured away from current model update the current model position.
 559              if ( ! _.isUndefined( self.current ) ) {
 560                  current = self.current;
 561              }
 562  
 563              // Get previous theme model.
 564              self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
 565  
 566              // If we have no more themes, bail.
 567              if ( _.isUndefined( self.current ) ) {
 568                  return;
 569              }
 570  
 571              preview.model = self.current;
 572  
 573              // Render and append.
 574              preview.render();
 575              this.setNavButtonsState();
 576              $( '.previous-theme' ).focus();
 577          });
 578  
 579          this.listenTo( preview, 'preview:close', function() {
 580              self.current = self.model;
 581          });
 582  
 583      },
 584  
 585      // Handles .disabled classes for previous/next buttons in theme installer preview.
 586      setNavButtonsState: function() {
 587          var $themeInstaller = $( '.theme-install-overlay' ),
 588              current = _.isUndefined( this.current ) ? this.model : this.current,
 589              previousThemeButton = $themeInstaller.find( '.previous-theme' ),
 590              nextThemeButton = $themeInstaller.find( '.next-theme' );
 591  
 592          // Disable previous at the zero position.
 593          if ( 0 === this.model.collection.indexOf( current ) ) {
 594              previousThemeButton
 595                  .addClass( 'disabled' )
 596                  .prop( 'disabled', true );
 597  
 598              nextThemeButton.focus();
 599          }
 600  
 601          // Disable next if the next model is undefined.
 602          if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
 603              nextThemeButton
 604                  .addClass( 'disabled' )
 605                  .prop( 'disabled', true );
 606  
 607              previousThemeButton.focus();
 608          }
 609      },
 610  
 611      installTheme: function( event ) {
 612          var _this = this;
 613  
 614          event.preventDefault();
 615  
 616          wp.updates.maybeRequestFilesystemCredentials( event );
 617  
 618          $( document ).on( 'wp-theme-install-success', function( event, response ) {
 619              if ( _this.model.get( 'id' ) === response.slug ) {
 620                  _this.model.set( { 'installed': true } );
 621              }
 622          } );
 623  
 624          wp.updates.installTheme( {
 625              slug: $( event.target ).data( 'slug' )
 626          } );
 627      },
 628  
 629      updateTheme: function( event ) {
 630          var _this = this;
 631  
 632          if ( ! this.model.get( 'hasPackage' ) ) {
 633              return;
 634          }
 635  
 636          event.preventDefault();
 637  
 638          wp.updates.maybeRequestFilesystemCredentials( event );
 639  
 640          $( document ).on( 'wp-theme-update-success', function( event, response ) {
 641              _this.model.off( 'change', _this.render, _this );
 642              if ( _this.model.get( 'id' ) === response.slug ) {
 643                  _this.model.set( {
 644                      hasUpdate: false,
 645                      version: response.newVersion
 646                  } );
 647              }
 648              _this.model.on( 'change', _this.render, _this );
 649          } );
 650  
 651          wp.updates.updateTheme( {
 652              slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
 653          } );
 654      }
 655  });
 656  
 657  // Theme Details view.
 658  // Sets up a modal overlay with the expanded theme data.
 659  themes.view.Details = wp.Backbone.View.extend({
 660  
 661      // Wrap theme data on a div.theme element.
 662      className: 'theme-overlay',
 663  
 664      events: {
 665          'click': 'collapse',
 666          'click .delete-theme': 'deleteTheme',
 667          'click .left': 'previousTheme',
 668          'click .right': 'nextTheme',
 669          'click #update-theme': 'updateTheme',
 670          'click .toggle-auto-update': 'autoupdateState'
 671      },
 672  
 673      // The HTML template for the theme overlay.
 674      html: themes.template( 'theme-single' ),
 675  
 676      render: function() {
 677          var data = this.model.toJSON();
 678          this.$el.html( this.html( data ) );
 679          // Renders active theme styles.
 680          this.activeTheme();
 681          // Set up navigation events.
 682          this.navigation();
 683          // Checks screenshot size.
 684          this.screenshotCheck( this.$el );
 685          // Contain "tabbing" inside the overlay.
 686          this.containFocus( this.$el );
 687      },
 688  
 689      // Adds a class to the currently active theme
 690      // and to the overlay in detailed view mode.
 691      activeTheme: function() {
 692          // Check the model has the active property.
 693          this.$el.toggleClass( 'active', this.model.get( 'active' ) );
 694      },
 695  
 696      // Set initial focus and constrain tabbing within the theme browser modal.
 697      containFocus: function( $el ) {
 698  
 699          // Set initial focus on the primary action control.
 700          _.delay( function() {
 701              $( '.theme-overlay' ).focus();
 702          }, 100 );
 703  
 704          // Constrain tabbing within the modal.
 705          $el.on( 'keydown.wp-themes', function( event ) {
 706              var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
 707                  $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
 708  
 709              // Check for the Tab key.
 710              if ( 9 === event.which ) {
 711                  if ( $firstFocusable[0] === event.target && event.shiftKey ) {
 712                      $lastFocusable.focus();
 713                      event.preventDefault();
 714                  } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
 715                      $firstFocusable.focus();
 716                      event.preventDefault();
 717                  }
 718              }
 719          });
 720      },
 721  
 722      // Single theme overlay screen.
 723      // It's shown when clicking a theme.
 724      collapse: function( event ) {
 725          var self = this,
 726              scroll;
 727  
 728          event = event || window.event;
 729  
 730          // Prevent collapsing detailed view when there is only one theme available.
 731          if ( themes.data.themes.length === 1 ) {
 732              return;
 733          }
 734  
 735          // Detect if the click is inside the overlay and don't close it
 736          // unless the target was the div.back button.
 737          if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
 738  
 739              // Add a temporary closing class while overlay fades out.
 740              $( 'body' ).addClass( 'closing-overlay' );
 741  
 742              // With a quick fade out animation.
 743              this.$el.fadeOut( 130, function() {
 744                  // Clicking outside the modal box closes the overlay.
 745                  $( 'body' ).removeClass( 'closing-overlay' );
 746                  // Handle event cleanup.
 747                  self.closeOverlay();
 748  
 749                  // Get scroll position to avoid jumping to the top.
 750                  scroll = document.body.scrollTop;
 751  
 752                  // Clean the URL structure.
 753                  themes.router.navigate( themes.router.baseUrl( '' ) );
 754  
 755                  // Restore scroll position.
 756                  document.body.scrollTop = scroll;
 757  
 758                  // Return focus to the theme div.
 759                  if ( themes.focusedTheme ) {
 760                      themes.focusedTheme.focus();
 761                  }
 762              });
 763          }
 764      },
 765  
 766      // Handles .disabled classes for next/previous buttons.
 767      navigation: function() {
 768  
 769          // Disable Left/Right when at the start or end of the collection.
 770          if ( this.model.cid === this.model.collection.at(0).cid ) {
 771              this.$el.find( '.left' )
 772                  .addClass( 'disabled' )
 773                  .prop( 'disabled', true );
 774          }
 775          if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
 776              this.$el.find( '.right' )
 777                  .addClass( 'disabled' )
 778                  .prop( 'disabled', true );
 779          }
 780      },
 781  
 782      // Performs the actions to effectively close
 783      // the theme details overlay.
 784      closeOverlay: function() {
 785          $( 'body' ).removeClass( 'modal-open' );
 786          this.remove();
 787          this.unbind();
 788          this.trigger( 'theme:collapse' );
 789      },
 790  
 791      // Set state of the auto-update settings link after it has been changed and saved.
 792      autoupdateState: function() {
 793          var callback,
 794              _this = this;
 795  
 796          // Support concurrent clicks in different Theme Details overlays.
 797          callback = function( event, data ) {
 798              if ( _this.model.get( 'id' ) === data.asset ) {
 799                  _this.model.set( { autoupdate: 'enable' === data.state } );
 800                  $( document ).off( 'wp-auto-update-setting-changed', callback );
 801              }
 802          };
 803  
 804          // Triggered in updates.js
 805          $( document ).on( 'wp-auto-update-setting-changed', callback );
 806      },
 807  
 808      updateTheme: function( event ) {
 809          var _this = this;
 810          event.preventDefault();
 811  
 812          wp.updates.maybeRequestFilesystemCredentials( event );
 813  
 814          $( document ).on( 'wp-theme-update-success', function( event, response ) {
 815              if ( _this.model.get( 'id' ) === response.slug ) {
 816                  _this.model.set( {
 817                      hasUpdate: false,
 818                      version: response.newVersion
 819                  } );
 820              }
 821              _this.render();
 822          } );
 823  
 824          wp.updates.updateTheme( {
 825              slug: $( event.target ).data( 'slug' )
 826          } );
 827      },
 828  
 829      deleteTheme: function( event ) {
 830          var _this = this,
 831              _collection = _this.model.collection,
 832              _themes = themes;
 833          event.preventDefault();
 834  
 835          // Confirmation dialog for deleting a theme.
 836          if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
 837              return;
 838          }
 839  
 840          wp.updates.maybeRequestFilesystemCredentials( event );
 841  
 842          $( document ).one( 'wp-theme-delete-success', function( event, response ) {
 843              _this.$el.find( '.close' ).trigger( 'click' );
 844              $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
 845                  $( this ).remove();
 846                  _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
 847  
 848                  $( '.wp-filter-search' ).val( '' );
 849                  _collection.doSearch( '' );
 850                  _collection.remove( _this.model );
 851                  _collection.trigger( 'themes:update' );
 852              } );
 853          } );
 854  
 855          wp.updates.deleteTheme( {
 856              slug: this.model.get( 'id' )
 857          } );
 858      },
 859  
 860      nextTheme: function() {
 861          var self = this;
 862          self.trigger( 'theme:next', self.model.cid );
 863          return false;
 864      },
 865  
 866      previousTheme: function() {
 867          var self = this;
 868          self.trigger( 'theme:previous', self.model.cid );
 869          return false;
 870      },
 871  
 872      // Checks if the theme screenshot is the old 300px width version
 873      // and adds a corresponding class if it's true.
 874      screenshotCheck: function( el ) {
 875          var screenshot, image;
 876  
 877          screenshot = el.find( '.screenshot img' );
 878          image = new Image();
 879          image.src = screenshot.attr( 'src' );
 880  
 881          // Width check.
 882          if ( image.width && image.width <= 300 ) {
 883              el.addClass( 'small-screenshot' );
 884          }
 885      }
 886  });
 887  
 888  // Theme Preview view.
 889  // Sets up a modal overlay with the expanded theme data.
 890  themes.view.Preview = themes.view.Details.extend({
 891  
 892      className: 'wp-full-overlay expanded',
 893      el: '.theme-install-overlay',
 894  
 895      events: {
 896          'click .close-full-overlay': 'close',
 897          'click .collapse-sidebar': 'collapse',
 898          'click .devices button': 'previewDevice',
 899          'click .previous-theme': 'previousTheme',
 900          'click .next-theme': 'nextTheme',
 901          'keyup': 'keyEvent',
 902          'click .theme-install': 'installTheme'
 903      },
 904  
 905      // The HTML template for the theme preview.
 906      html: themes.template( 'theme-preview' ),
 907  
 908      render: function() {
 909          var self = this,
 910              currentPreviewDevice,
 911              data = this.model.toJSON(),
 912              $body = $( document.body );
 913  
 914          $body.attr( 'aria-busy', 'true' );
 915  
 916          this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
 917  
 918          currentPreviewDevice = this.$el.data( 'current-preview-device' );
 919          if ( currentPreviewDevice ) {
 920              self.tooglePreviewDeviceButtons( currentPreviewDevice );
 921          }
 922  
 923          themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: false } );
 924  
 925          this.$el.fadeIn( 200, function() {
 926              $body.addClass( 'theme-installer-active full-overlay-active' );
 927          });
 928  
 929          this.$el.find( 'iframe' ).one( 'load', function() {
 930              self.iframeLoaded();
 931          });
 932      },
 933  
 934      iframeLoaded: function() {
 935          this.$el.addClass( 'iframe-ready' );
 936          $( document.body ).attr( 'aria-busy', 'false' );
 937      },
 938  
 939      close: function() {
 940          this.$el.fadeOut( 200, function() {
 941              $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
 942  
 943              // Return focus to the theme div.
 944              if ( themes.focusedTheme ) {
 945                  themes.focusedTheme.focus();
 946              }
 947          }).removeClass( 'iframe-ready' );
 948  
 949          // Restore the previous browse tab if available.
 950          if ( themes.router.selectedTab ) {
 951              themes.router.navigate( themes.router.baseUrl( '?browse=' + themes.router.selectedTab ) );
 952              themes.router.selectedTab = false;
 953          } else {
 954              themes.router.navigate( themes.router.baseUrl( '' ) );
 955          }
 956          this.trigger( 'preview:close' );
 957          this.undelegateEvents();
 958          this.unbind();
 959          return false;
 960      },
 961  
 962      collapse: function( event ) {
 963          var $button = $( event.currentTarget );
 964          if ( 'true' === $button.attr( 'aria-expanded' ) ) {
 965              $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
 966          } else {
 967              $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
 968          }
 969  
 970          this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
 971          return false;
 972      },
 973  
 974      previewDevice: function( event ) {
 975          var device = $( event.currentTarget ).data( 'device' );
 976  
 977          this.$el
 978              .removeClass( 'preview-desktop preview-tablet preview-mobile' )
 979              .addClass( 'preview-' + device )
 980              .data( 'current-preview-device', device );
 981  
 982          this.tooglePreviewDeviceButtons( device );
 983      },
 984  
 985      tooglePreviewDeviceButtons: function( newDevice ) {
 986          var $devices = $( '.wp-full-overlay-footer .devices' );
 987  
 988          $devices.find( 'button' )
 989              .removeClass( 'active' )
 990              .attr( 'aria-pressed', false );
 991  
 992          $devices.find( 'button.preview-' + newDevice )
 993              .addClass( 'active' )
 994              .attr( 'aria-pressed', true );
 995      },
 996  
 997      keyEvent: function( event ) {
 998          // The escape key closes the preview.
 999          if ( event.keyCode === 27 ) {
1000              this.undelegateEvents();
1001              this.close();
1002          }
1003          // The right arrow key, next theme.
1004          if ( event.keyCode === 39 ) {
1005              _.once( this.nextTheme() );
1006          }
1007  
1008          // The left arrow key, previous theme.
1009          if ( event.keyCode === 37 ) {
1010              this.previousTheme();
1011          }
1012      },
1013  
1014      installTheme: function( event ) {
1015          var _this   = this,
1016              $target = $( event.target );
1017          event.preventDefault();
1018  
1019          if ( $target.hasClass( 'disabled' ) ) {
1020              return;
1021          }
1022  
1023          wp.updates.maybeRequestFilesystemCredentials( event );
1024  
1025          $( document ).on( 'wp-theme-install-success', function() {
1026              _this.model.set( { 'installed': true } );
1027          } );
1028  
1029          wp.updates.installTheme( {
1030              slug: $target.data( 'slug' )
1031          } );
1032      }
1033  });
1034  
1035  // Controls the rendering of div.themes,
1036  // a wrapper that will hold all the theme elements.
1037  themes.view.Themes = wp.Backbone.View.extend({
1038  
1039      className: 'themes wp-clearfix',
1040      $overlay: $( 'div.theme-overlay' ),
1041  
1042      // Number to keep track of scroll position
1043      // while in theme-overlay mode.
1044      index: 0,
1045  
1046      // The theme count element.
1047      count: $( '.wrap .theme-count' ),
1048  
1049      // The live themes count.
1050      liveThemeCount: 0,
1051  
1052      initialize: function( options ) {
1053          var self = this;
1054  
1055          // Set up parent.
1056          this.parent = options.parent;
1057  
1058          // Set current view to [grid].
1059          this.setView( 'grid' );
1060  
1061          // Move the active theme to the beginning of the collection.
1062          self.currentTheme();
1063  
1064          // When the collection is updated by user input...
1065          this.listenTo( self.collection, 'themes:update', function() {
1066              self.parent.page = 0;
1067              self.currentTheme();
1068              self.render( this );
1069          } );
1070  
1071          // Update theme count to full result set when available.
1072          this.listenTo( self.collection, 'query:success', function( count ) {
1073              if ( _.isNumber( count ) ) {
1074                  self.count.text( count );
1075                  self.announceSearchResults( count );
1076              } else {
1077                  self.count.text( self.collection.length );
1078                  self.announceSearchResults( self.collection.length );
1079              }
1080          });
1081  
1082          this.listenTo( self.collection, 'query:empty', function() {
1083              $( 'body' ).addClass( 'no-results' );
1084          });
1085  
1086          this.listenTo( this.parent, 'theme:scroll', function() {
1087              self.renderThemes( self.parent.page );
1088          });
1089  
1090          this.listenTo( this.parent, 'theme:close', function() {
1091              if ( self.overlay ) {
1092                  self.overlay.closeOverlay();
1093              }
1094          } );
1095  
1096          // Bind keyboard events.
1097          $( 'body' ).on( 'keyup', function( event ) {
1098              if ( ! self.overlay ) {
1099                  return;
1100              }
1101  
1102              // Bail if the filesystem credentials dialog is shown.
1103              if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
1104                  return;
1105              }
1106  
1107              // Pressing the right arrow key fires a theme:next event.
1108              if ( event.keyCode === 39 ) {
1109                  self.overlay.nextTheme();
1110              }
1111  
1112              // Pressing the left arrow key fires a theme:previous event.
1113              if ( event.keyCode === 37 ) {
1114                  self.overlay.previousTheme();
1115              }
1116  
1117              // Pressing the escape key fires a theme:collapse event.
1118              if ( event.keyCode === 27 ) {
1119                  self.overlay.collapse( event );
1120              }
1121          });
1122      },
1123  
1124      // Manages rendering of theme pages
1125      // and keeping theme count in sync.
1126      render: function() {
1127          // Clear the DOM, please.
1128          this.$el.empty();
1129  
1130          // If the user doesn't have switch capabilities or there is only one theme
1131          // in the collection, render the detailed view of the active theme.
1132          if ( themes.data.themes.length === 1 ) {
1133  
1134              // Constructs the view.
1135              this.singleTheme = new themes.view.Details({
1136                  model: this.collection.models[0]
1137              });
1138  
1139              // Render and apply a 'single-theme' class to our container.
1140              this.singleTheme.render();
1141              this.$el.addClass( 'single-theme' );
1142              this.$el.append( this.singleTheme.el );
1143          }
1144  
1145          // Generate the themes using page instance
1146          // while checking the collection has items.
1147          if ( this.options.collection.size() > 0 ) {
1148              this.renderThemes( this.parent.page );
1149          }
1150  
1151          // Display a live theme count for the collection.
1152          this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
1153          this.count.text( this.liveThemeCount );
1154  
1155          /*
1156           * In the theme installer the themes count is already announced
1157           * because `announceSearchResults` is called on `query:success`.
1158           */
1159          if ( ! themes.isInstall ) {
1160              this.announceSearchResults( this.liveThemeCount );
1161          }
1162      },
1163  
1164      // Iterates through each instance of the collection
1165      // and renders each theme module.
1166      renderThemes: function( page ) {
1167          var self = this;
1168  
1169          self.instance = self.collection.paginate( page );
1170  
1171          // If we have no more themes, bail.
1172          if ( self.instance.size() === 0 ) {
1173              // Fire a no-more-themes event.
1174              this.parent.trigger( 'theme:end' );
1175              return;
1176          }
1177  
1178          // Make sure the add-new stays at the end.
1179          if ( ! themes.isInstall && page >= 1 ) {
1180              $( '.add-new-theme' ).remove();
1181          }
1182  
1183          // Loop through the themes and setup each theme view.
1184          self.instance.each( function( theme ) {
1185              self.theme = new themes.view.Theme({
1186                  model: theme,
1187                  parent: self
1188              });
1189  
1190              // Render the views...
1191              self.theme.render();
1192              // ...and append them to div.themes.
1193              self.$el.append( self.theme.el );
1194  
1195              // Binds to theme:expand to show the modal box
1196              // with the theme details.
1197              self.listenTo( self.theme, 'theme:expand', self.expand, self );
1198          });
1199  
1200          // 'Add new theme' element shown at the end of the grid.
1201          if ( ! themes.isInstall && themes.data.settings.canInstall ) {
1202              this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' );
1203          }
1204  
1205          this.parent.page++;
1206      },
1207  
1208      // Grabs current theme and puts it at the beginning of the collection.
1209      currentTheme: function() {
1210          var self = this,
1211              current;
1212  
1213          current = self.collection.findWhere({ active: true });
1214  
1215          // Move the active theme to the beginning of the collection.
1216          if ( current ) {
1217              self.collection.remove( current );
1218              self.collection.add( current, { at:0 } );
1219          }
1220      },
1221  
1222      // Sets current view.
1223      setView: function( view ) {
1224          return view;
1225      },
1226  
1227      // Renders the overlay with the ThemeDetails view.
1228      // Uses the current model data.
1229      expand: function( id ) {
1230          var self = this, $card, $modal;
1231  
1232          // Set the current theme model.
1233          this.model = self.collection.get( id );
1234  
1235          // Trigger a route update for the current model.
1236          themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1237  
1238          // Sets this.view to 'detail'.
1239          this.setView( 'detail' );
1240          $( 'body' ).addClass( 'modal-open' );
1241  
1242          // Set up the theme details view.
1243          this.overlay = new themes.view.Details({
1244              model: self.model
1245          });
1246  
1247          this.overlay.render();
1248  
1249          if ( this.model.get( 'hasUpdate' ) ) {
1250              $card  = $( '[data-slug="' + this.model.id + '"]' );
1251              $modal = $( this.overlay.el );
1252  
1253              if ( $card.find( '.updating-message' ).length ) {
1254                  $modal.find( '.notice-warning h3' ).remove();
1255                  $modal.find( '.notice-warning' )
1256                      .removeClass( 'notice-large' )
1257                      .addClass( 'updating-message' )
1258                      .find( 'p' ).text( wp.updates.l10n.updating );
1259              } else if ( $card.find( '.notice-error' ).length ) {
1260                  $modal.find( '.notice-warning' ).remove();
1261              }
1262          }
1263  
1264          this.$overlay.html( this.overlay.el );
1265  
1266          // Bind to theme:next and theme:previous triggered by the arrow keys.
1267          // Keep track of the current model so we can infer an index position.
1268          this.listenTo( this.overlay, 'theme:next', function() {
1269              // Renders the next theme on the overlay.
1270              self.next( [ self.model.cid ] );
1271  
1272          })
1273          .listenTo( this.overlay, 'theme:previous', function() {
1274              // Renders the previous theme on the overlay.
1275              self.previous( [ self.model.cid ] );
1276          });
1277      },
1278  
1279      /*
1280       * This method renders the next theme on the overlay modal
1281       * based on the current position in the collection.
1282       *
1283       * @params [model cid]
1284       */
1285      next: function( args ) {
1286          var self = this,
1287              model, nextModel;
1288  
1289          // Get the current theme.
1290          model = self.collection.get( args[0] );
1291          // Find the next model within the collection.
1292          nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1293  
1294          // Sanity check which also serves as a boundary test.
1295          if ( nextModel !== undefined ) {
1296  
1297              // We have a new theme...
1298              // Close the overlay.
1299              this.overlay.closeOverlay();
1300  
1301              // Trigger a route update for the current model.
1302              self.theme.trigger( 'theme:expand', nextModel.cid );
1303  
1304          }
1305      },
1306  
1307      /*
1308       * This method renders the previous theme on the overlay modal
1309       * based on the current position in the collection.
1310       *
1311       * @params [model cid]
1312       */
1313      previous: function( args ) {
1314          var self = this,
1315              model, previousModel;
1316  
1317          // Get the current theme.
1318          model = self.collection.get( args[0] );
1319          // Find the previous model within the collection.
1320          previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1321  
1322          if ( previousModel !== undefined ) {
1323  
1324              // We have a new theme...
1325              // Close the overlay.
1326              this.overlay.closeOverlay();
1327  
1328              // Trigger a route update for the current model.
1329              self.theme.trigger( 'theme:expand', previousModel.cid );
1330  
1331          }
1332      },
1333  
1334      // Dispatch audible search results feedback message.
1335      announceSearchResults: function( count ) {
1336          if ( 0 === count ) {
1337              wp.a11y.speak( l10n.noThemesFound );
1338          } else {
1339              wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1340          }
1341      }
1342  });
1343  
1344  // Search input view controller.
1345  themes.view.Search = wp.Backbone.View.extend({
1346  
1347      tagName: 'input',
1348      className: 'wp-filter-search',
1349      id: 'wp-filter-search-input',
1350      searching: false,
1351  
1352      attributes: {
1353          placeholder: l10n.searchPlaceholder,
1354          type: 'search',
1355          'aria-describedby': 'live-search-desc'
1356      },
1357  
1358      events: {
1359          'input': 'search',
1360          'keyup': 'search',
1361          'blur': 'pushState'
1362      },
1363  
1364      initialize: function( options ) {
1365  
1366          this.parent = options.parent;
1367  
1368          this.listenTo( this.parent, 'theme:close', function() {
1369              this.searching = false;
1370          } );
1371  
1372      },
1373  
1374      search: function( event ) {
1375          // Clear on escape.
1376          if ( event.type === 'keyup' && event.which === 27 ) {
1377              event.target.value = '';
1378          }
1379  
1380          // Since doSearch is debounced, it will only run when user input comes to a rest.
1381          this.doSearch( event );
1382      },
1383  
1384      // Runs a search on the theme collection.
1385      doSearch: function( event ) {
1386          var options = {};
1387  
1388          this.collection.doSearch( event.target.value.replace( /\+/g, ' ' ) );
1389  
1390          // if search is initiated and key is not return.
1391          if ( this.searching && event.which !== 13 ) {
1392              options.replace = true;
1393          } else {
1394              this.searching = true;
1395          }
1396  
1397          // Update the URL hash.
1398          if ( event.target.value ) {
1399              themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1400          } else {
1401              themes.router.navigate( themes.router.baseUrl( '' ) );
1402          }
1403      },
1404  
1405      pushState: function( event ) {
1406          var url = themes.router.baseUrl( '' );
1407  
1408          if ( event.target.value ) {
1409              url = themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( event.target.value ) );
1410          }
1411  
1412          this.searching = false;
1413          themes.router.navigate( url );
1414  
1415      }
1416  });
1417  
1418  /**
1419   * Navigate router.
1420   *
1421   * @since 4.9.0
1422   *
1423   * @param {string} url - URL to navigate to.
1424   * @param {object} state - State.
1425   * @return {void}
1426   */
1427  function navigateRouter( url, state ) {
1428      var router = this;
1429      if ( Backbone.history._hasPushState ) {
1430          Backbone.Router.prototype.navigate.call( router, url, state );
1431      }
1432  }
1433  
1434  // Sets up the routes events for relevant url queries.
1435  // Listens to [theme] and [search] params.
1436  themes.Router = Backbone.Router.extend({
1437  
1438      routes: {
1439          'themes.php?theme=:slug': 'theme',
1440          'themes.php?search=:query': 'search',
1441          'themes.php?s=:query': 'search',
1442          'themes.php': 'themes',
1443          '': 'themes'
1444      },
1445  
1446      baseUrl: function( url ) {
1447          return 'themes.php' + url;
1448      },
1449  
1450      themePath: '?theme=',
1451      searchPath: '?search=',
1452  
1453      search: function( query ) {
1454          $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
1455      },
1456  
1457      themes: function() {
1458          $( '.wp-filter-search' ).val( '' );
1459      },
1460  
1461      navigate: navigateRouter
1462  
1463  });
1464  
1465  // Execute and setup the application.
1466  themes.Run = {
1467      init: function() {
1468          // Initializes the blog's theme library view.
1469          // Create a new collection with data.
1470          this.themes = new themes.Collection( themes.data.themes );
1471  
1472          // Set up the view.
1473          this.view = new themes.view.Appearance({
1474              collection: this.themes
1475          });
1476  
1477          this.render();
1478  
1479          // Start debouncing user searches after Backbone.history.start().
1480          this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
1481      },
1482  
1483      render: function() {
1484  
1485          // Render results.
1486          this.view.render();
1487          this.routes();
1488  
1489          if ( Backbone.History.started ) {
1490              Backbone.history.stop();
1491          }
1492          Backbone.history.start({
1493              root: themes.data.settings.adminUrl,
1494              pushState: true,
1495              hashChange: false
1496          });
1497      },
1498  
1499      routes: function() {
1500          var self = this;
1501          // Bind to our global thx object
1502          // so that the object is available to sub-views.
1503          themes.router = new themes.Router();
1504  
1505          // Handles theme details route event.
1506          themes.router.on( 'route:theme', function( slug ) {
1507              self.view.view.expand( slug );
1508          });
1509  
1510          themes.router.on( 'route:themes', function() {
1511              self.themes.doSearch( '' );
1512              self.view.trigger( 'theme:close' );
1513          });
1514  
1515          // Handles search route event.
1516          themes.router.on( 'route:search', function() {
1517              $( '.wp-filter-search' ).trigger( 'keyup' );
1518          });
1519  
1520          this.extraRoutes();
1521      },
1522  
1523      extraRoutes: function() {
1524          return false;
1525      }
1526  };
1527  
1528  // Extend the main Search view.
1529  themes.view.InstallerSearch =  themes.view.Search.extend({
1530  
1531      events: {
1532          'input': 'search',
1533          'keyup': 'search'
1534      },
1535  
1536      terms: '',
1537  
1538      // Handles Ajax request for searching through themes in public repo.
1539      search: function( event ) {
1540  
1541          // Tabbing or reverse tabbing into the search input shouldn't trigger a search.
1542          if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1543              return;
1544          }
1545  
1546          this.collection = this.options.parent.view.collection;
1547  
1548          // Clear on escape.
1549          if ( event.type === 'keyup' && event.which === 27 ) {
1550              event.target.value = '';
1551          }
1552  
1553          this.doSearch( event.target.value );
1554      },
1555  
1556      doSearch: function( value ) {
1557          var request = {};
1558  
1559          // Don't do anything if the search terms haven't changed.
1560          if ( this.terms === value ) {
1561              return;
1562          }
1563  
1564          // Updates terms with the value passed.
1565          this.terms = value;
1566  
1567          request.search = value;
1568  
1569          /*
1570           * Intercept an [author] search.
1571           *
1572           * If input value starts with `author:` send a request
1573           * for `author` instead of a regular `search`.
1574           */
1575          if ( value.substring( 0, 7 ) === 'author:' ) {
1576              request.search = '';
1577              request.author = value.slice( 7 );
1578          }
1579  
1580          /*
1581           * Intercept a [tag] search.
1582           *
1583           * If input value starts with `tag:` send a request
1584           * for `tag` instead of a regular `search`.
1585           */
1586          if ( value.substring( 0, 4 ) === 'tag:' ) {
1587              request.search = '';
1588              request.tag = [ value.slice( 4 ) ];
1589          }
1590  
1591          $( '.filter-links li > a.current' )
1592              .removeClass( 'current' )
1593              .removeAttr( 'aria-current' );
1594  
1595          $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
1596          $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1597  
1598          // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1599          // or searching the local cache.
1600          this.collection.query( request );
1601  
1602          // Set route.
1603          themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( value ) ), { replace: true } );
1604      }
1605  });
1606  
1607  themes.view.Installer = themes.view.Appearance.extend({
1608  
1609      el: '#wpbody-content .wrap',
1610  
1611      // Register events for sorting and filters in theme-navigation.
1612      events: {
1613          'click .filter-links li > a': 'onSort',
1614          'click .theme-filter': 'onFilter',
1615          'click .drawer-toggle': 'moreFilters',
1616          'click .filter-drawer .apply-filters': 'applyFilters',
1617          'click .filter-group [type="checkbox"]': 'addFilter',
1618          'click .filter-drawer .clear-filters': 'clearFilters',
1619          'click .edit-filters': 'backToFilters',
1620          'click .favorites-form-submit' : 'saveUsername',
1621          'keyup #wporg-username-input': 'saveUsername'
1622      },
1623  
1624      // Initial render method.
1625      render: function() {
1626          var self = this;
1627  
1628          this.search();
1629          this.uploader();
1630  
1631          this.collection = new themes.Collection();
1632  
1633          // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1634          this.listenTo( this, 'theme:end', function() {
1635  
1636              // Make sure we are not already loading.
1637              if ( self.collection.loadingThemes ) {
1638                  return;
1639              }
1640  
1641              // Set loadingThemes to true and bump page instance of currentQuery.
1642              self.collection.loadingThemes = true;
1643              self.collection.currentQuery.page++;
1644  
1645              // Use currentQuery.page to build the themes request.
1646              _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1647              self.collection.query( self.collection.currentQuery.request );
1648          });
1649  
1650          this.listenTo( this.collection, 'query:success', function() {
1651              $( 'body' ).removeClass( 'loading-content' );
1652              $( '.theme-browser' ).find( 'div.error' ).remove();
1653          });
1654  
1655          this.listenTo( this.collection, 'query:fail', function() {
1656              $( 'body' ).removeClass( 'loading-content' );
1657              $( '.theme-browser' ).find( 'div.error' ).remove();
1658              $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p><p><button class="button try-again">' + l10n.tryAgain + '</button></p></div>' );
1659              $( '.theme-browser .error .try-again' ).on( 'click', function( e ) {
1660                  e.preventDefault();
1661                  $( 'input.wp-filter-search' ).trigger( 'input' );
1662              } );
1663          });
1664  
1665          if ( this.view ) {
1666              this.view.remove();
1667          }
1668  
1669          // Sets up the view and passes the section argument.
1670          this.view = new themes.view.Themes({
1671              collection: this.collection,
1672              parent: this
1673          });
1674  
1675          // Reset pagination every time the install view handler is run.
1676          this.page = 0;
1677  
1678          // Render and append.
1679          this.$el.find( '.themes' ).remove();
1680          this.view.render();
1681          this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1682      },
1683  
1684      // Handles all the rendering of the public theme directory.
1685      browse: function( section ) {
1686          // Create a new collection with the proper theme data
1687          // for each section.
1688          this.collection.query( { browse: section } );
1689      },
1690  
1691      // Sorting navigation.
1692      onSort: function( event ) {
1693          var $el = $( event.target ),
1694              sort = $el.data( 'sort' );
1695  
1696          event.preventDefault();
1697  
1698          $( 'body' ).removeClass( 'filters-applied show-filters' );
1699          $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1700  
1701          // Bail if this is already active.
1702          if ( $el.hasClass( this.activeClass ) ) {
1703              return;
1704          }
1705  
1706          this.sort( sort );
1707  
1708          // Trigger a router.navigate update.
1709          themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1710      },
1711  
1712      sort: function( sort ) {
1713          this.clearSearch();
1714  
1715          // Track sorting so we can restore the correct tab when closing preview.
1716          themes.router.selectedTab = sort;
1717  
1718          $( '.filter-links li > a, .theme-filter' )
1719              .removeClass( this.activeClass )
1720              .removeAttr( 'aria-current' );
1721  
1722          $( '[data-sort="' + sort + '"]' )
1723              .addClass( this.activeClass )
1724              .attr( 'aria-current', 'page' );
1725  
1726          if ( 'favorites' === sort ) {
1727              $( 'body' ).addClass( 'show-favorites-form' );
1728          } else {
1729              $( 'body' ).removeClass( 'show-favorites-form' );
1730          }
1731  
1732          this.browse( sort );
1733      },
1734  
1735      // Filters and Tags.
1736      onFilter: function( event ) {
1737          var request,
1738              $el = $( event.target ),
1739              filter = $el.data( 'filter' );
1740  
1741          // Bail if this is already active.
1742          if ( $el.hasClass( this.activeClass ) ) {
1743              return;
1744          }
1745  
1746          $( '.filter-links li > a, .theme-section' )
1747              .removeClass( this.activeClass )
1748              .removeAttr( 'aria-current' );
1749          $el
1750              .addClass( this.activeClass )
1751              .attr( 'aria-current', 'page' );
1752  
1753          if ( ! filter ) {
1754              return;
1755          }
1756  
1757          // Construct the filter request
1758          // using the default values.
1759          filter = _.union( [ filter, this.filtersChecked() ] );
1760          request = { tag: [ filter ] };
1761  
1762          // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1763          // or searching the local cache.
1764          this.collection.query( request );
1765      },
1766  
1767      // Clicking on a checkbox to add another filter to the request.
1768      addFilter: function() {
1769          this.filtersChecked();
1770      },
1771  
1772      // Applying filters triggers a tag request.
1773      applyFilters: function( event ) {
1774          var name,
1775              tags = this.filtersChecked(),
1776              request = { tag: tags },
1777              filteringBy = $( '.filtered-by .tags' );
1778  
1779          if ( event ) {
1780              event.preventDefault();
1781          }
1782  
1783          if ( ! tags ) {
1784              wp.a11y.speak( l10n.selectFeatureFilter );
1785              return;
1786          }
1787  
1788          $( 'body' ).addClass( 'filters-applied' );
1789          $( '.filter-links li > a.current' )
1790              .removeClass( 'current' )
1791              .removeAttr( 'aria-current' );
1792  
1793          filteringBy.empty();
1794  
1795          _.each( tags, function( tag ) {
1796              name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1797              filteringBy.append( '<span class="tag">' + name + '</span>' );
1798          });
1799  
1800          // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1801          // or searching the local cache.
1802          this.collection.query( request );
1803      },
1804  
1805      // Save the user's WordPress.org username and get his favorite themes.
1806      saveUsername: function ( event ) {
1807          var username = $( '#wporg-username-input' ).val(),
1808              nonce = $( '#wporg-username-nonce' ).val(),
1809              request = { browse: 'favorites', user: username },
1810              that = this;
1811  
1812          if ( event ) {
1813              event.preventDefault();
1814          }
1815  
1816          // Save username on enter.
1817          if ( event.type === 'keyup' && event.which !== 13 ) {
1818              return;
1819          }
1820  
1821          return wp.ajax.send( 'save-wporg-username', {
1822              data: {
1823                  _wpnonce: nonce,
1824                  username: username
1825              },
1826              success: function () {
1827                  // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1828                  // or searching the local cache.
1829                  that.collection.query( request );
1830              }
1831          } );
1832      },
1833  
1834      /**
1835       * Get the checked filters.
1836       *
1837       * @return {array} of tags or false
1838       */
1839      filtersChecked: function() {
1840          var items = $( '.filter-group' ).find( ':checkbox' ),
1841              tags = [];
1842  
1843          _.each( items.filter( ':checked' ), function( item ) {
1844              tags.push( $( item ).prop( 'value' ) );
1845          });
1846  
1847          // When no filters are checked, restore initial state and return.
1848          if ( tags.length === 0 ) {
1849              $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1850              $( '.filter-drawer .clear-filters' ).hide();
1851              $( 'body' ).removeClass( 'filters-applied' );
1852              return false;
1853          }
1854  
1855          $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1856          $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1857  
1858          return tags;
1859      },
1860  
1861      activeClass: 'current',
1862  
1863      /**
1864       * When users press the "Upload Theme" button, show the upload form in place.
1865       */
1866      uploader: function() {
1867          var uploadViewToggle = $( '.upload-view-toggle' ),
1868              $body = $( document.body );
1869  
1870          uploadViewToggle.on( 'click', function() {
1871              // Toggle the upload view.
1872              $body.toggleClass( 'show-upload-view' );
1873              // Toggle the `aria-expanded` button attribute.
1874              uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
1875          });
1876      },
1877  
1878      // Toggle the full filters navigation.
1879      moreFilters: function( event ) {
1880          var $body = $( 'body' ),
1881              $toggleButton = $( '.drawer-toggle' );
1882  
1883          event.preventDefault();
1884  
1885          if ( $body.hasClass( 'filters-applied' ) ) {
1886              return this.backToFilters();
1887          }
1888  
1889          this.clearSearch();
1890  
1891          themes.router.navigate( themes.router.baseUrl( '' ) );
1892          // Toggle the feature filters view.
1893          $body.toggleClass( 'show-filters' );
1894          // Toggle the `aria-expanded` button attribute.
1895          $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
1896      },
1897  
1898      /**
1899       * Clears all the checked filters.
1900       *
1901       * @uses filtersChecked()
1902       */
1903      clearFilters: function( event ) {
1904          var items = $( '.filter-group' ).find( ':checkbox' ),
1905              self = this;
1906  
1907          event.preventDefault();
1908  
1909          _.each( items.filter( ':checked' ), function( item ) {
1910              $( item ).prop( 'checked', false );
1911              return self.filtersChecked();
1912          });
1913      },
1914  
1915      backToFilters: function( event ) {
1916          if ( event ) {
1917              event.preventDefault();
1918          }
1919  
1920          $( 'body' ).removeClass( 'filters-applied' );
1921      },
1922  
1923      clearSearch: function() {
1924          $( '#wp-filter-search-input').val( '' );
1925      }
1926  });
1927  
1928  themes.InstallerRouter = Backbone.Router.extend({
1929      routes: {
1930          'theme-install.php?theme=:slug': 'preview',
1931          'theme-install.php?browse=:sort': 'sort',
1932          'theme-install.php?search=:query': 'search',
1933          'theme-install.php': 'sort'
1934      },
1935  
1936      baseUrl: function( url ) {
1937          return 'theme-install.php' + url;
1938      },
1939  
1940      themePath: '?theme=',
1941      browsePath: '?browse=',
1942      searchPath: '?search=',
1943  
1944      search: function( query ) {
1945          $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
1946      },
1947  
1948      navigate: navigateRouter
1949  });
1950  
1951  
1952  themes.RunInstaller = {
1953  
1954      init: function() {
1955          // Set up the view.
1956          // Passes the default 'section' as an option.
1957          this.view = new themes.view.Installer({
1958              section: 'featured',
1959              SearchView: themes.view.InstallerSearch
1960          });
1961  
1962          // Render results.
1963          this.render();
1964  
1965          // Start debouncing user searches after Backbone.history.start().
1966          this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
1967      },
1968  
1969      render: function() {
1970  
1971          // Render results.
1972          this.view.render();
1973          this.routes();
1974  
1975          if ( Backbone.History.started ) {
1976              Backbone.history.stop();
1977          }
1978          Backbone.history.start({
1979              root: themes.data.settings.adminUrl,
1980              pushState: true,
1981              hashChange: false
1982          });
1983      },
1984  
1985      routes: function() {
1986          var self = this,
1987              request = {};
1988  
1989          // Bind to our global `wp.themes` object
1990          // so that the router is available to sub-views.
1991          themes.router = new themes.InstallerRouter();
1992  
1993          // Handles `theme` route event.
1994          // Queries the API for the passed theme slug.
1995          themes.router.on( 'route:preview', function( slug ) {
1996  
1997              // Remove existing handlers.
1998              if ( themes.preview ) {
1999                  themes.preview.undelegateEvents();
2000                  themes.preview.unbind();
2001              }
2002  
2003              // If the theme preview is active, set the current theme.
2004              if ( self.view.view.theme && self.view.view.theme.preview ) {
2005                  self.view.view.theme.model = self.view.collection.findWhere( { 'slug': slug } );
2006                  self.view.view.theme.preview();
2007              } else {
2008  
2009                  // Select the theme by slug.
2010                  request.theme = slug;
2011                  self.view.collection.query( request );
2012                  self.view.collection.trigger( 'update' );
2013  
2014                  // Open the theme preview.
2015                  self.view.collection.once( 'query:success', function() {
2016                      $( 'div[data-slug="' + slug + '"]' ).trigger( 'click' );
2017                  });
2018  
2019              }
2020          });
2021  
2022          /*
2023           * Handles sorting / browsing routes.
2024           * Also handles the root URL triggering a sort request
2025           * for `featured`, the default view.
2026           */
2027          themes.router.on( 'route:sort', function( sort ) {
2028              if ( ! sort ) {
2029                  sort = 'featured';
2030                  themes.router.navigate( themes.router.baseUrl( '?browse=featured' ), { replace: true } );
2031              }
2032              self.view.sort( sort );
2033  
2034              // Close the preview if open.
2035              if ( themes.preview ) {
2036                  themes.preview.close();
2037              }
2038          });
2039  
2040          // The `search` route event. The router populates the input field.
2041          themes.router.on( 'route:search', function() {
2042              $( '.wp-filter-search' ).focus().trigger( 'keyup' );
2043          });
2044  
2045          this.extraRoutes();
2046      },
2047  
2048      extraRoutes: function() {
2049          return false;
2050      }
2051  };
2052  
2053  // Ready...
2054  $( document ).ready(function() {
2055      if ( themes.isInstall ) {
2056          themes.RunInstaller.init();
2057      } else {
2058          themes.Run.init();
2059      }
2060  
2061      // Update the return param just in time.
2062      $( document.body ).on( 'click', '.load-customize', function() {
2063          var link = $( this ), urlParser = document.createElement( 'a' );
2064          urlParser.href = link.prop( 'href' );
2065          urlParser.search = $.param( _.extend(
2066              wp.customize.utils.parseQueryString( urlParser.search.substr( 1 ) ),
2067              {
2068                  'return': window.location.href
2069              }
2070          ) );
2071          link.prop( 'href', urlParser.href );
2072      });
2073  
2074      $( '.broken-themes .delete-theme' ).on( 'click', function() {
2075          return confirm( _wpThemeSettings.settings.confirmDelete );
2076      });
2077  });
2078  
2079  })( jQuery );
2080  
2081  // Align theme browser thickbox.
2082  jQuery(document).ready( function($) {
2083      window.tb_position = function() {
2084          var tbWindow = $('#TB_window'),
2085              width = $(window).width(),
2086              H = $(window).height(),
2087              W = ( 1040 < width ) ? 1040 : width,
2088              adminbar_height = 0;
2089  
2090          if ( $('#wpadminbar').length ) {
2091              adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
2092          }
2093  
2094          if ( tbWindow.size() ) {
2095              tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
2096              $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
2097              tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
2098              if ( typeof document.body.style.maxWidth !== 'undefined' ) {
2099                  tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
2100              }
2101          }
2102      };
2103  
2104      $(window).resize(function(){ tb_position(); });
2105  });


Generated: Tue Jun 2 01:00:03 2020 Cross-referenced by PHPXref 0.7.1