[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Sat Nov 23 20:47:33 2019 Cross-referenced by PHPXref 0.7