/wp-admin/js/theme.js

https://gitlab.com/em645jn/brochure · JavaScript · 1903 lines · 1163 code · 397 blank · 343 comment · 143 complexity · ff91d4e4b9f6dbcd0c761c54010972b7 MD5 · raw file

  1. /* global _wpThemeSettings, confirm */
  2. window.wp = window.wp || {};
  3. ( function($) {
  4. // Set up our namespace...
  5. var themes, l10n;
  6. themes = wp.themes = wp.themes || {};
  7. // Store the theme data and settings for organized and quick access
  8. // themes.data.settings, themes.data.themes, themes.data.l10n
  9. themes.data = _wpThemeSettings;
  10. l10n = themes.data.l10n;
  11. // Shortcut for isInstall check
  12. themes.isInstall = !! themes.data.settings.isInstall;
  13. // Setup app structure
  14. _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
  15. themes.Model = Backbone.Model.extend({
  16. // Adds attributes to the default data coming through the .org themes api
  17. // Map `id` to `slug` for shared code
  18. initialize: function() {
  19. var description;
  20. // If theme is already installed, set an attribute.
  21. if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
  22. this.set({ installed: true });
  23. }
  24. // Set the attributes
  25. this.set({
  26. // slug is for installation, id is for existing.
  27. id: this.get( 'slug' ) || this.get( 'id' )
  28. });
  29. // Map `section.description` to `description`
  30. // as the API sometimes returns it differently
  31. if ( this.has( 'sections' ) ) {
  32. description = this.get( 'sections' ).description;
  33. this.set({ description: description });
  34. }
  35. }
  36. });
  37. // Main view controller for themes.php
  38. // Unifies and renders all available views
  39. themes.view.Appearance = wp.Backbone.View.extend({
  40. el: '#wpbody-content .wrap .theme-browser',
  41. window: $( window ),
  42. // Pagination instance
  43. page: 0,
  44. // Sets up a throttler for binding to 'scroll'
  45. initialize: function( options ) {
  46. // Scroller checks how far the scroll position is
  47. _.bindAll( this, 'scroller' );
  48. this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
  49. // Bind to the scroll event and throttle
  50. // the results from this.scroller
  51. this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
  52. },
  53. // Main render control
  54. render: function() {
  55. // Setup the main theme view
  56. // with the current theme collection
  57. this.view = new themes.view.Themes({
  58. collection: this.collection,
  59. parent: this
  60. });
  61. // Render search form.
  62. this.search();
  63. // Render and append
  64. this.view.render();
  65. this.$el.empty().append( this.view.el ).addClass( 'rendered' );
  66. },
  67. // Defines search element container
  68. searchContainer: $( '#wpbody h1:first' ),
  69. // Search input and view
  70. // for current theme collection
  71. search: function() {
  72. var view,
  73. self = this;
  74. // Don't render the search if there is only one theme
  75. if ( themes.data.themes.length === 1 ) {
  76. return;
  77. }
  78. view = new this.SearchView({
  79. collection: self.collection,
  80. parent: this
  81. });
  82. // Render and append after screen title
  83. view.render();
  84. this.searchContainer
  85. .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
  86. .append( view.el );
  87. },
  88. // Checks when the user gets close to the bottom
  89. // of the mage and triggers a theme:scroll event
  90. scroller: function() {
  91. var self = this,
  92. bottom, threshold;
  93. bottom = this.window.scrollTop() + self.window.height();
  94. threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
  95. threshold = Math.round( threshold * 0.9 );
  96. if ( bottom > threshold ) {
  97. this.trigger( 'theme:scroll' );
  98. }
  99. }
  100. });
  101. // Set up the Collection for our theme data
  102. // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
  103. themes.Collection = Backbone.Collection.extend({
  104. model: themes.Model,
  105. // Search terms
  106. terms: '',
  107. // Controls searching on the current theme collection
  108. // and triggers an update event
  109. doSearch: function( value ) {
  110. // Don't do anything if we've already done this search
  111. // Useful because the Search handler fires multiple times per keystroke
  112. if ( this.terms === value ) {
  113. return;
  114. }
  115. // Updates terms with the value passed
  116. this.terms = value;
  117. // If we have terms, run a search...
  118. if ( this.terms.length > 0 ) {
  119. this.search( this.terms );
  120. }
  121. // If search is blank, show all themes
  122. // Useful for resetting the views when you clean the input
  123. if ( this.terms === '' ) {
  124. this.reset( themes.data.themes );
  125. $( 'body' ).removeClass( 'no-results' );
  126. }
  127. // Trigger a 'themes:update' event
  128. this.trigger( 'themes:update' );
  129. },
  130. // Performs a search within the collection
  131. // @uses RegExp
  132. search: function( term ) {
  133. var match, results, haystack, name, description, author;
  134. // Start with a full collection
  135. this.reset( themes.data.themes, { silent: true } );
  136. // Escape the term string for RegExp meta characters
  137. term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
  138. // Consider spaces as word delimiters and match the whole string
  139. // so matching terms can be combined
  140. term = term.replace( / /g, ')(?=.*' );
  141. match = new RegExp( '^(?=.*' + term + ').+', 'i' );
  142. // Find results
  143. // _.filter and .test
  144. results = this.filter( function( data ) {
  145. name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
  146. description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
  147. author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
  148. haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
  149. if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
  150. data.set( 'displayAuthor', true );
  151. }
  152. return match.test( haystack );
  153. });
  154. if ( results.length === 0 ) {
  155. this.trigger( 'query:empty' );
  156. } else {
  157. $( 'body' ).removeClass( 'no-results' );
  158. }
  159. this.reset( results );
  160. },
  161. // Paginates the collection with a helper method
  162. // that slices the collection
  163. paginate: function( instance ) {
  164. var collection = this;
  165. instance = instance || 0;
  166. // Themes per instance are set at 20
  167. collection = _( collection.rest( 20 * instance ) );
  168. collection = _( collection.first( 20 ) );
  169. return collection;
  170. },
  171. count: false,
  172. // Handles requests for more themes
  173. // and caches results
  174. //
  175. // When we are missing a cache object we fire an apiCall()
  176. // which triggers events of `query:success` or `query:fail`
  177. query: function( request ) {
  178. /**
  179. * @static
  180. * @type Array
  181. */
  182. var queries = this.queries,
  183. self = this,
  184. query, isPaginated, count;
  185. // Store current query request args
  186. // for later use with the event `theme:end`
  187. this.currentQuery.request = request;
  188. // Search the query cache for matches.
  189. query = _.find( queries, function( query ) {
  190. return _.isEqual( query.request, request );
  191. });
  192. // If the request matches the stored currentQuery.request
  193. // it means we have a paginated request.
  194. isPaginated = _.has( request, 'page' );
  195. // Reset the internal api page counter for non paginated queries.
  196. if ( ! isPaginated ) {
  197. this.currentQuery.page = 1;
  198. }
  199. // Otherwise, send a new API call and add it to the cache.
  200. if ( ! query && ! isPaginated ) {
  201. query = this.apiCall( request ).done( function( data ) {
  202. // Update the collection with the queried data.
  203. if ( data.themes ) {
  204. self.reset( data.themes );
  205. count = data.info.results;
  206. // Store the results and the query request
  207. queries.push( { themes: data.themes, request: request, total: count } );
  208. }
  209. // Trigger a collection refresh event
  210. // and a `query:success` event with a `count` argument.
  211. self.trigger( 'themes:update' );
  212. self.trigger( 'query:success', count );
  213. if ( data.themes && data.themes.length === 0 ) {
  214. self.trigger( 'query:empty' );
  215. }
  216. }).fail( function() {
  217. self.trigger( 'query:fail' );
  218. });
  219. } else {
  220. // If it's a paginated request we need to fetch more themes...
  221. if ( isPaginated ) {
  222. return this.apiCall( request, isPaginated ).done( function( data ) {
  223. // Add the new themes to the current collection
  224. // @todo update counter
  225. self.add( data.themes );
  226. self.trigger( 'query:success' );
  227. // We are done loading themes for now.
  228. self.loadingThemes = false;
  229. }).fail( function() {
  230. self.trigger( 'query:fail' );
  231. });
  232. }
  233. if ( query.themes.length === 0 ) {
  234. self.trigger( 'query:empty' );
  235. } else {
  236. $( 'body' ).removeClass( 'no-results' );
  237. }
  238. // Only trigger an update event since we already have the themes
  239. // on our cached object
  240. if ( _.isNumber( query.total ) ) {
  241. this.count = query.total;
  242. }
  243. this.reset( query.themes );
  244. if ( ! query.total ) {
  245. this.count = this.length;
  246. }
  247. this.trigger( 'themes:update' );
  248. this.trigger( 'query:success', this.count );
  249. }
  250. },
  251. // Local cache array for API queries
  252. queries: [],
  253. // Keep track of current query so we can handle pagination
  254. currentQuery: {
  255. page: 1,
  256. request: {}
  257. },
  258. // Send request to api.wordpress.org/themes
  259. apiCall: function( request, paginated ) {
  260. return wp.ajax.send( 'query-themes', {
  261. data: {
  262. // Request data
  263. request: _.extend({
  264. per_page: 100,
  265. fields: {
  266. description: true,
  267. tested: true,
  268. requires: true,
  269. rating: true,
  270. downloaded: true,
  271. downloadLink: true,
  272. last_updated: true,
  273. homepage: true,
  274. num_ratings: true
  275. }
  276. }, request)
  277. },
  278. beforeSend: function() {
  279. if ( ! paginated ) {
  280. // Spin it
  281. $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
  282. }
  283. }
  284. });
  285. },
  286. // Static status controller for when we are loading themes.
  287. loadingThemes: false
  288. });
  289. // This is the view that controls each theme item
  290. // that will be displayed on the screen
  291. themes.view.Theme = wp.Backbone.View.extend({
  292. // Wrap theme data on a div.theme element
  293. className: 'theme',
  294. // Reflects which theme view we have
  295. // 'grid' (default) or 'detail'
  296. state: 'grid',
  297. // The HTML template for each element to be rendered
  298. html: themes.template( 'theme' ),
  299. events: {
  300. 'click': themes.isInstall ? 'preview': 'expand',
  301. 'keydown': themes.isInstall ? 'preview': 'expand',
  302. 'touchend': themes.isInstall ? 'preview': 'expand',
  303. 'keyup': 'addFocus',
  304. 'touchmove': 'preventExpand',
  305. 'click .theme-install': 'installTheme',
  306. 'click .update-message': 'updateTheme'
  307. },
  308. touchDrag: false,
  309. initialize: function() {
  310. this.model.on( 'change', this.render, this );
  311. },
  312. render: function() {
  313. var data = this.model.toJSON();
  314. // Render themes using the html template
  315. this.$el.html( this.html( data ) ).attr({
  316. tabindex: 0,
  317. 'aria-describedby' : data.id + '-action ' + data.id + '-name',
  318. 'data-slug': data.id
  319. });
  320. // Renders active theme styles
  321. this.activeTheme();
  322. if ( this.model.get( 'displayAuthor' ) ) {
  323. this.$el.addClass( 'display-author' );
  324. }
  325. },
  326. // Adds a class to the currently active theme
  327. // and to the overlay in detailed view mode
  328. activeTheme: function() {
  329. if ( this.model.get( 'active' ) ) {
  330. this.$el.addClass( 'active' );
  331. }
  332. },
  333. // Add class of focus to the theme we are focused on.
  334. addFocus: function() {
  335. var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
  336. $('.theme.focus').removeClass('focus');
  337. $themeToFocus.addClass('focus');
  338. },
  339. // Single theme overlay screen
  340. // It's shown when clicking a theme
  341. expand: function( event ) {
  342. var self = this;
  343. event = event || window.event;
  344. // 'enter' and 'space' keys expand the details view when a theme is :focused
  345. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  346. return;
  347. }
  348. // Bail if the user scrolled on a touch device
  349. if ( this.touchDrag === true ) {
  350. return this.touchDrag = false;
  351. }
  352. // Prevent the modal from showing when the user clicks
  353. // one of the direct action buttons
  354. if ( $( event.target ).is( '.theme-actions a' ) ) {
  355. return;
  356. }
  357. // Prevent the modal from showing when the user clicks one of the direct action buttons.
  358. if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) {
  359. return;
  360. }
  361. // Set focused theme to current element
  362. themes.focusedTheme = this.$el;
  363. this.trigger( 'theme:expand', self.model.cid );
  364. },
  365. preventExpand: function() {
  366. this.touchDrag = true;
  367. },
  368. preview: function( event ) {
  369. var self = this,
  370. current, preview;
  371. event = event || window.event;
  372. // Bail if the user scrolled on a touch device
  373. if ( this.touchDrag === true ) {
  374. return this.touchDrag = false;
  375. }
  376. // Allow direct link path to installing a theme.
  377. if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) {
  378. return;
  379. }
  380. // 'enter' and 'space' keys expand the details view when a theme is :focused
  381. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  382. return;
  383. }
  384. // pressing enter while focused on the buttons shouldn't open the preview
  385. if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
  386. return;
  387. }
  388. event.preventDefault();
  389. event = event || window.event;
  390. // Set focus to current theme.
  391. themes.focusedTheme = this.$el;
  392. // Construct a new Preview view.
  393. preview = new themes.view.Preview({
  394. model: this.model
  395. });
  396. // Render the view and append it.
  397. preview.render();
  398. this.setNavButtonsState();
  399. // Hide previous/next navigation if there is only one theme
  400. if ( this.model.collection.length === 1 ) {
  401. preview.$el.addClass( 'no-navigation' );
  402. } else {
  403. preview.$el.removeClass( 'no-navigation' );
  404. }
  405. // Append preview
  406. $( 'div.wrap' ).append( preview.el );
  407. // Listen to our preview object
  408. // for `theme:next` and `theme:previous` events.
  409. this.listenTo( preview, 'theme:next', function() {
  410. // Keep local track of current theme model.
  411. current = self.model;
  412. // If we have ventured away from current model update the current model position.
  413. if ( ! _.isUndefined( self.current ) ) {
  414. current = self.current;
  415. }
  416. // Get next theme model.
  417. self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
  418. // If we have no more themes, bail.
  419. if ( _.isUndefined( self.current ) ) {
  420. self.options.parent.parent.trigger( 'theme:end' );
  421. return self.current = current;
  422. }
  423. preview.model = self.current;
  424. // Render and append.
  425. preview.render();
  426. this.setNavButtonsState();
  427. $( '.next-theme' ).focus();
  428. })
  429. .listenTo( preview, 'theme:previous', function() {
  430. // Keep track of current theme model.
  431. current = self.model;
  432. // Bail early if we are at the beginning of the collection
  433. if ( self.model.collection.indexOf( self.current ) === 0 ) {
  434. return;
  435. }
  436. // If we have ventured away from current model update the current model position.
  437. if ( ! _.isUndefined( self.current ) ) {
  438. current = self.current;
  439. }
  440. // Get previous theme model.
  441. self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
  442. // If we have no more themes, bail.
  443. if ( _.isUndefined( self.current ) ) {
  444. return;
  445. }
  446. preview.model = self.current;
  447. // Render and append.
  448. preview.render();
  449. this.setNavButtonsState();
  450. $( '.previous-theme' ).focus();
  451. });
  452. this.listenTo( preview, 'preview:close', function() {
  453. self.current = self.model;
  454. });
  455. },
  456. // Handles .disabled classes for previous/next buttons in theme installer preview
  457. setNavButtonsState: function() {
  458. var $themeInstaller = $( '.theme-install-overlay' ),
  459. current = _.isUndefined( this.current ) ? this.model : this.current;
  460. // Disable previous at the zero position
  461. if ( 0 === this.model.collection.indexOf( current ) ) {
  462. $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
  463. }
  464. // Disable next if the next model is undefined
  465. if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
  466. $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
  467. }
  468. },
  469. installTheme: function( event ) {
  470. var _this = this;
  471. event.preventDefault();
  472. wp.updates.maybeRequestFilesystemCredentials( event );
  473. $( document ).on( 'wp-theme-install-success', function( event, response ) {
  474. if ( _this.model.get( 'id' ) === response.slug ) {
  475. _this.model.set( { 'installed': true } );
  476. }
  477. } );
  478. wp.updates.installTheme( {
  479. slug: $( event.target ).data( 'slug' )
  480. } );
  481. },
  482. updateTheme: function( event ) {
  483. var _this = this;
  484. event.preventDefault();
  485. wp.updates.maybeRequestFilesystemCredentials( event );
  486. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  487. _this.model.off( 'change', _this.render, _this );
  488. if ( _this.model.get( 'id' ) === response.slug ) {
  489. _this.model.set( {
  490. hasUpdate: false,
  491. version: response.newVersion
  492. } );
  493. }
  494. _this.model.on( 'change', _this.render, _this );
  495. } );
  496. wp.updates.updateTheme( {
  497. slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
  498. } );
  499. }
  500. });
  501. // Theme Details view
  502. // Set ups a modal overlay with the expanded theme data
  503. themes.view.Details = wp.Backbone.View.extend({
  504. // Wrap theme data on a div.theme element
  505. className: 'theme-overlay',
  506. events: {
  507. 'click': 'collapse',
  508. 'click .delete-theme': 'deleteTheme',
  509. 'click .left': 'previousTheme',
  510. 'click .right': 'nextTheme',
  511. 'click #update-theme': 'updateTheme'
  512. },
  513. // The HTML template for the theme overlay
  514. html: themes.template( 'theme-single' ),
  515. render: function() {
  516. var data = this.model.toJSON();
  517. this.$el.html( this.html( data ) );
  518. // Renders active theme styles
  519. this.activeTheme();
  520. // Set up navigation events
  521. this.navigation();
  522. // Checks screenshot size
  523. this.screenshotCheck( this.$el );
  524. // Contain "tabbing" inside the overlay
  525. this.containFocus( this.$el );
  526. },
  527. // Adds a class to the currently active theme
  528. // and to the overlay in detailed view mode
  529. activeTheme: function() {
  530. // Check the model has the active property
  531. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  532. },
  533. // Set initial focus and constrain tabbing within the theme browser modal.
  534. containFocus: function( $el ) {
  535. // Set initial focus on the primary action control.
  536. _.delay( function() {
  537. $( '.theme-wrap a.button-primary:visible' ).focus();
  538. }, 100 );
  539. // Constrain tabbing within the modal.
  540. $el.on( 'keydown.wp-themes', function( event ) {
  541. var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
  542. $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
  543. // Check for the Tab key.
  544. if ( 9 === event.which ) {
  545. if ( $firstFocusable[0] === event.target && event.shiftKey ) {
  546. $lastFocusable.focus();
  547. event.preventDefault();
  548. } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
  549. $firstFocusable.focus();
  550. event.preventDefault();
  551. }
  552. }
  553. });
  554. },
  555. // Single theme overlay screen
  556. // It's shown when clicking a theme
  557. collapse: function( event ) {
  558. var self = this,
  559. scroll;
  560. event = event || window.event;
  561. // Prevent collapsing detailed view when there is only one theme available
  562. if ( themes.data.themes.length === 1 ) {
  563. return;
  564. }
  565. // Detect if the click is inside the overlay
  566. // and don't close it unless the target was
  567. // the div.back button
  568. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
  569. // Add a temporary closing class while overlay fades out
  570. $( 'body' ).addClass( 'closing-overlay' );
  571. // With a quick fade out animation
  572. this.$el.fadeOut( 130, function() {
  573. // Clicking outside the modal box closes the overlay
  574. $( 'body' ).removeClass( 'closing-overlay' );
  575. // Handle event cleanup
  576. self.closeOverlay();
  577. // Get scroll position to avoid jumping to the top
  578. scroll = document.body.scrollTop;
  579. // Clean the url structure
  580. themes.router.navigate( themes.router.baseUrl( '' ) );
  581. // Restore scroll position
  582. document.body.scrollTop = scroll;
  583. // Return focus to the theme div
  584. if ( themes.focusedTheme ) {
  585. themes.focusedTheme.focus();
  586. }
  587. });
  588. }
  589. },
  590. // Handles .disabled classes for next/previous buttons
  591. navigation: function() {
  592. // Disable Left/Right when at the start or end of the collection
  593. if ( this.model.cid === this.model.collection.at(0).cid ) {
  594. this.$el.find( '.left' )
  595. .addClass( 'disabled' )
  596. .prop( 'disabled', true );
  597. }
  598. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  599. this.$el.find( '.right' )
  600. .addClass( 'disabled' )
  601. .prop( 'disabled', true );
  602. }
  603. },
  604. // Performs the actions to effectively close
  605. // the theme details overlay
  606. closeOverlay: function() {
  607. $( 'body' ).removeClass( 'modal-open' );
  608. this.remove();
  609. this.unbind();
  610. this.trigger( 'theme:collapse' );
  611. },
  612. updateTheme: function( event ) {
  613. var _this = this;
  614. event.preventDefault();
  615. wp.updates.maybeRequestFilesystemCredentials( event );
  616. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  617. if ( _this.model.get( 'id' ) === response.slug ) {
  618. _this.model.set( {
  619. hasUpdate: false,
  620. version: response.newVersion
  621. } );
  622. }
  623. _this.render();
  624. } );
  625. wp.updates.updateTheme( {
  626. slug: $( event.target ).data( 'slug' )
  627. } );
  628. },
  629. deleteTheme: function( event ) {
  630. var _this = this,
  631. _collection = _this.model.collection,
  632. _themes = themes;
  633. event.preventDefault();
  634. // Confirmation dialog for deleting a theme.
  635. if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
  636. return;
  637. }
  638. wp.updates.maybeRequestFilesystemCredentials( event );
  639. $( document ).one( 'wp-theme-delete-success', function( event, response ) {
  640. _this.$el.find( '.close' ).trigger( 'click' );
  641. $( '[data-slug="' + response.slug + '"' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
  642. $( this ).remove();
  643. _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
  644. $( '.wp-filter-search' ).val( '' );
  645. _collection.doSearch( '' );
  646. _collection.remove( _this.model );
  647. _collection.trigger( 'themes:update' );
  648. } );
  649. } );
  650. wp.updates.deleteTheme( {
  651. slug: this.model.get( 'id' )
  652. } );
  653. },
  654. nextTheme: function() {
  655. var self = this;
  656. self.trigger( 'theme:next', self.model.cid );
  657. return false;
  658. },
  659. previousTheme: function() {
  660. var self = this;
  661. self.trigger( 'theme:previous', self.model.cid );
  662. return false;
  663. },
  664. // Checks if the theme screenshot is the old 300px width version
  665. // and adds a corresponding class if it's true
  666. screenshotCheck: function( el ) {
  667. var screenshot, image;
  668. screenshot = el.find( '.screenshot img' );
  669. image = new Image();
  670. image.src = screenshot.attr( 'src' );
  671. // Width check
  672. if ( image.width && image.width <= 300 ) {
  673. el.addClass( 'small-screenshot' );
  674. }
  675. }
  676. });
  677. // Theme Preview view
  678. // Set ups a modal overlay with the expanded theme data
  679. themes.view.Preview = themes.view.Details.extend({
  680. className: 'wp-full-overlay expanded',
  681. el: '.theme-install-overlay',
  682. events: {
  683. 'click .close-full-overlay': 'close',
  684. 'click .collapse-sidebar': 'collapse',
  685. 'click .devices button': 'previewDevice',
  686. 'click .previous-theme': 'previousTheme',
  687. 'click .next-theme': 'nextTheme',
  688. 'keyup': 'keyEvent',
  689. 'click .theme-install': 'installTheme'
  690. },
  691. // The HTML template for the theme preview
  692. html: themes.template( 'theme-preview' ),
  693. render: function() {
  694. var self = this, currentPreviewDevice,
  695. data = this.model.toJSON();
  696. this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
  697. currentPreviewDevice = this.$el.data( 'current-preview-device' );
  698. if ( currentPreviewDevice ) {
  699. self.tooglePreviewDeviceButtons( currentPreviewDevice );
  700. }
  701. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
  702. this.$el.fadeIn( 200, function() {
  703. $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
  704. $( '.close-full-overlay' ).focus();
  705. });
  706. this.$el.find( 'iframe' ).one( 'load', function() {
  707. self.iframeLoaded();
  708. });
  709. },
  710. iframeLoaded: function() {
  711. this.$el.addClass( 'iframe-ready' );
  712. },
  713. close: function() {
  714. this.$el.fadeOut( 200, function() {
  715. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  716. // Return focus to the theme div
  717. if ( themes.focusedTheme ) {
  718. themes.focusedTheme.focus();
  719. }
  720. }).removeClass( 'iframe-ready' );
  721. themes.router.navigate( themes.router.baseUrl( '' ) );
  722. this.trigger( 'preview:close' );
  723. this.undelegateEvents();
  724. this.unbind();
  725. return false;
  726. },
  727. collapse: function( event ) {
  728. var $button = $( event.currentTarget );
  729. if ( 'true' === $button.attr( 'aria-expanded' ) ) {
  730. $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
  731. } else {
  732. $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
  733. }
  734. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  735. return false;
  736. },
  737. previewDevice: function( event ) {
  738. var device = $( event.currentTarget ).data( 'device' );
  739. this.$el
  740. .removeClass( 'preview-desktop preview-tablet preview-mobile' )
  741. .addClass( 'preview-' + device )
  742. .data( 'current-preview-device', device );
  743. this.tooglePreviewDeviceButtons( device );
  744. },
  745. tooglePreviewDeviceButtons: function( newDevice ) {
  746. var $devices = $( '.wp-full-overlay-footer .devices' );
  747. $devices.find( 'button' )
  748. .removeClass( 'active' )
  749. .attr( 'aria-pressed', false );
  750. $devices.find( 'button.preview-' + newDevice )
  751. .addClass( 'active' )
  752. .attr( 'aria-pressed', true );
  753. },
  754. keyEvent: function( event ) {
  755. // The escape key closes the preview
  756. if ( event.keyCode === 27 ) {
  757. this.undelegateEvents();
  758. this.close();
  759. }
  760. // The right arrow key, next theme
  761. if ( event.keyCode === 39 ) {
  762. _.once( this.nextTheme() );
  763. }
  764. // The left arrow key, previous theme
  765. if ( event.keyCode === 37 ) {
  766. this.previousTheme();
  767. }
  768. },
  769. installTheme: function( event ) {
  770. var _this = this,
  771. $target = $( event.target );
  772. event.preventDefault();
  773. if ( $target.hasClass( 'disabled' ) ) {
  774. return;
  775. }
  776. wp.updates.maybeRequestFilesystemCredentials( event );
  777. $( document ).on( 'wp-theme-install-success', function() {
  778. _this.model.set( { 'installed': true } );
  779. } );
  780. wp.updates.installTheme( {
  781. slug: $target.data( 'slug' )
  782. } );
  783. }
  784. });
  785. // Controls the rendering of div.themes,
  786. // a wrapper that will hold all the theme elements
  787. themes.view.Themes = wp.Backbone.View.extend({
  788. className: 'themes wp-clearfix',
  789. $overlay: $( 'div.theme-overlay' ),
  790. // Number to keep track of scroll position
  791. // while in theme-overlay mode
  792. index: 0,
  793. // The theme count element
  794. count: $( '.wrap .theme-count' ),
  795. // The live themes count
  796. liveThemeCount: 0,
  797. initialize: function( options ) {
  798. var self = this;
  799. // Set up parent
  800. this.parent = options.parent;
  801. // Set current view to [grid]
  802. this.setView( 'grid' );
  803. // Move the active theme to the beginning of the collection
  804. self.currentTheme();
  805. // When the collection is updated by user input...
  806. this.listenTo( self.collection, 'themes:update', function() {
  807. self.parent.page = 0;
  808. self.currentTheme();
  809. self.render( this );
  810. } );
  811. // Update theme count to full result set when available.
  812. this.listenTo( self.collection, 'query:success', function( count ) {
  813. if ( _.isNumber( count ) ) {
  814. self.count.text( count );
  815. self.announceSearchResults( count );
  816. } else {
  817. self.count.text( self.collection.length );
  818. self.announceSearchResults( self.collection.length );
  819. }
  820. });
  821. this.listenTo( self.collection, 'query:empty', function() {
  822. $( 'body' ).addClass( 'no-results' );
  823. });
  824. this.listenTo( this.parent, 'theme:scroll', function() {
  825. self.renderThemes( self.parent.page );
  826. });
  827. this.listenTo( this.parent, 'theme:close', function() {
  828. if ( self.overlay ) {
  829. self.overlay.closeOverlay();
  830. }
  831. } );
  832. // Bind keyboard events.
  833. $( 'body' ).on( 'keyup', function( event ) {
  834. if ( ! self.overlay ) {
  835. return;
  836. }
  837. // Bail if the filesystem credentials dialog is shown.
  838. if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
  839. return;
  840. }
  841. // Pressing the right arrow key fires a theme:next event
  842. if ( event.keyCode === 39 ) {
  843. self.overlay.nextTheme();
  844. }
  845. // Pressing the left arrow key fires a theme:previous event
  846. if ( event.keyCode === 37 ) {
  847. self.overlay.previousTheme();
  848. }
  849. // Pressing the escape key fires a theme:collapse event
  850. if ( event.keyCode === 27 ) {
  851. self.overlay.collapse( event );
  852. }
  853. });
  854. },
  855. // Manages rendering of theme pages
  856. // and keeping theme count in sync
  857. render: function() {
  858. // Clear the DOM, please
  859. this.$el.empty();
  860. // If the user doesn't have switch capabilities
  861. // or there is only one theme in the collection
  862. // render the detailed view of the active theme
  863. if ( themes.data.themes.length === 1 ) {
  864. // Constructs the view
  865. this.singleTheme = new themes.view.Details({
  866. model: this.collection.models[0]
  867. });
  868. // Render and apply a 'single-theme' class to our container
  869. this.singleTheme.render();
  870. this.$el.addClass( 'single-theme' );
  871. this.$el.append( this.singleTheme.el );
  872. }
  873. // Generate the themes
  874. // Using page instance
  875. // While checking the collection has items
  876. if ( this.options.collection.size() > 0 ) {
  877. this.renderThemes( this.parent.page );
  878. }
  879. // Display a live theme count for the collection
  880. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  881. this.count.text( this.liveThemeCount );
  882. /*
  883. * In the theme installer the themes count is already announced
  884. * because `announceSearchResults` is called on `query:success`.
  885. */
  886. if ( ! themes.isInstall ) {
  887. this.announceSearchResults( this.liveThemeCount );
  888. }
  889. },
  890. // Iterates through each instance of the collection
  891. // and renders each theme module
  892. renderThemes: function( page ) {
  893. var self = this;
  894. self.instance = self.collection.paginate( page );
  895. // If we have no more themes bail
  896. if ( self.instance.size() === 0 ) {
  897. // Fire a no-more-themes event.
  898. this.parent.trigger( 'theme:end' );
  899. return;
  900. }
  901. // Make sure the add-new stays at the end
  902. if ( ! themes.isInstall && page >= 1 ) {
  903. $( '.add-new-theme' ).remove();
  904. }
  905. // Loop through the themes and setup each theme view
  906. self.instance.each( function( theme ) {
  907. self.theme = new themes.view.Theme({
  908. model: theme,
  909. parent: self
  910. });
  911. // Render the views...
  912. self.theme.render();
  913. // and append them to div.themes
  914. self.$el.append( self.theme.el );
  915. // Binds to theme:expand to show the modal box
  916. // with the theme details
  917. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  918. });
  919. // 'Add new theme' element shown at the end of the grid
  920. if ( ! themes.isInstall && themes.data.settings.canInstall ) {
  921. 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>' );
  922. }
  923. this.parent.page++;
  924. },
  925. // Grabs current theme and puts it at the beginning of the collection
  926. currentTheme: function() {
  927. var self = this,
  928. current;
  929. current = self.collection.findWhere({ active: true });
  930. // Move the active theme to the beginning of the collection
  931. if ( current ) {
  932. self.collection.remove( current );
  933. self.collection.add( current, { at:0 } );
  934. }
  935. },
  936. // Sets current view
  937. setView: function( view ) {
  938. return view;
  939. },
  940. // Renders the overlay with the ThemeDetails view
  941. // Uses the current model data
  942. expand: function( id ) {
  943. var self = this, $card, $modal;
  944. // Set the current theme model
  945. this.model = self.collection.get( id );
  946. // Trigger a route update for the current model
  947. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  948. // Sets this.view to 'detail'
  949. this.setView( 'detail' );
  950. $( 'body' ).addClass( 'modal-open' );
  951. // Set up the theme details view
  952. this.overlay = new themes.view.Details({
  953. model: self.model
  954. });
  955. this.overlay.render();
  956. if ( this.model.get( 'hasUpdate' ) ) {
  957. $card = $( '[data-slug="' + this.model.id + '"]' );
  958. $modal = $( this.overlay.el );
  959. if ( $card.find( '.updating-message' ).length ) {
  960. $modal.find( '.notice-warning h3' ).remove();
  961. $modal.find( '.notice-warning' )
  962. .removeClass( 'notice-large' )
  963. .addClass( 'updating-message' )
  964. .find( 'p' ).text( wp.updates.l10n.updating );
  965. } else if ( $card.find( '.notice-error' ).length ) {
  966. $modal.find( '.notice-warning' ).remove();
  967. }
  968. }
  969. this.$overlay.html( this.overlay.el );
  970. // Bind to theme:next and theme:previous
  971. // triggered by the arrow keys
  972. //
  973. // Keep track of the current model so we
  974. // can infer an index position
  975. this.listenTo( this.overlay, 'theme:next', function() {
  976. // Renders the next theme on the overlay
  977. self.next( [ self.model.cid ] );
  978. })
  979. .listenTo( this.overlay, 'theme:previous', function() {
  980. // Renders the previous theme on the overlay
  981. self.previous( [ self.model.cid ] );
  982. });
  983. },
  984. // This method renders the next theme on the overlay modal
  985. // based on the current position in the collection
  986. // @params [model cid]
  987. next: function( args ) {
  988. var self = this,
  989. model, nextModel;
  990. // Get the current theme
  991. model = self.collection.get( args[0] );
  992. // Find the next model within the collection
  993. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  994. // Sanity check which also serves as a boundary test
  995. if ( nextModel !== undefined ) {
  996. // We have a new theme...
  997. // Close the overlay
  998. this.overlay.closeOverlay();
  999. // Trigger a route update for the current model
  1000. self.theme.trigger( 'theme:expand', nextModel.cid );
  1001. }
  1002. },
  1003. // This method renders the previous theme on the overlay modal
  1004. // based on the current position in the collection
  1005. // @params [model cid]
  1006. previous: function( args ) {
  1007. var self = this,
  1008. model, previousModel;
  1009. // Get the current theme
  1010. model = self.collection.get( args[0] );
  1011. // Find the previous model within the collection
  1012. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  1013. if ( previousModel !== undefined ) {
  1014. // We have a new theme...
  1015. // Close the overlay
  1016. this.overlay.closeOverlay();
  1017. // Trigger a route update for the current model
  1018. self.theme.trigger( 'theme:expand', previousModel.cid );
  1019. }
  1020. },
  1021. // Dispatch audible search results feedback message
  1022. announceSearchResults: function( count ) {
  1023. if ( 0 === count ) {
  1024. wp.a11y.speak( l10n.noThemesFound );
  1025. } else {
  1026. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  1027. }
  1028. }
  1029. });
  1030. // Search input view controller.
  1031. themes.view.Search = wp.Backbone.View.extend({
  1032. tagName: 'input',
  1033. className: 'wp-filter-search',
  1034. id: 'wp-filter-search-input',
  1035. searching: false,
  1036. attributes: {
  1037. placeholder: l10n.searchPlaceholder,
  1038. type: 'search',
  1039. 'aria-describedby': 'live-search-desc'
  1040. },
  1041. events: {
  1042. 'input': 'search',
  1043. 'keyup': 'search',
  1044. 'blur': 'pushState'
  1045. },
  1046. initialize: function( options ) {
  1047. this.parent = options.parent;
  1048. this.listenTo( this.parent, 'theme:close', function() {
  1049. this.searching = false;
  1050. } );
  1051. },
  1052. search: function( event ) {
  1053. // Clear on escape.
  1054. if ( event.type === 'keyup' && event.which === 27 ) {
  1055. event.target.value = '';
  1056. }
  1057. /**
  1058. * Since doSearch is debounced, it will only run when user input comes to a rest
  1059. */
  1060. this.doSearch( event );
  1061. },
  1062. // Runs a search on the theme collection.
  1063. doSearch: _.debounce( function( event ) {
  1064. var options = {};
  1065. this.collection.doSearch( event.target.value );
  1066. // if search is initiated and key is not return
  1067. if ( this.searching && event.which !== 13 ) {
  1068. options.replace = true;
  1069. } else {
  1070. this.searching = true;
  1071. }
  1072. // Update the URL hash
  1073. if ( event.target.value ) {
  1074. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  1075. } else {
  1076. themes.router.navigate( themes.router.baseUrl( '' ) );
  1077. }
  1078. }, 500 ),
  1079. pushState: function( event ) {
  1080. var url = themes.router.baseUrl( '' );
  1081. if ( event.target.value ) {
  1082. url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
  1083. }
  1084. this.searching = false;
  1085. themes.router.navigate( url );
  1086. }
  1087. });
  1088. // Sets up the routes events for relevant url queries
  1089. // Listens to [theme] and [search] params
  1090. themes.Router = Backbone.Router.extend({
  1091. routes: {
  1092. 'themes.php?theme=:slug': 'theme',
  1093. 'themes.php?search=:query': 'search',
  1094. 'themes.php?s=:query': 'search',
  1095. 'themes.php': 'themes',
  1096. '': 'themes'
  1097. },
  1098. baseUrl: function( url ) {
  1099. return 'themes.php' + url;
  1100. },
  1101. themePath: '?theme=',
  1102. searchPath: '?search=',
  1103. search: function( query ) {
  1104. $( '.wp-filter-search' ).val( query );
  1105. },
  1106. themes: function() {
  1107. $( '.wp-filter-search' ).val( '' );
  1108. },
  1109. navigate: function() {
  1110. if ( Backbone.history._hasPushState ) {
  1111. Backbone.Router.prototype.navigate.apply( this, arguments );
  1112. }
  1113. }
  1114. });
  1115. // Execute and setup the application
  1116. themes.Run = {
  1117. init: function() {
  1118. // Initializes the blog's theme library view
  1119. // Create a new collection with data
  1120. this.themes = new themes.Collection( themes.data.themes );
  1121. // Set up the view
  1122. this.view = new themes.view.Appearance({
  1123. collection: this.themes
  1124. });
  1125. this.render();
  1126. },
  1127. render: function() {
  1128. // Render results
  1129. this.view.render();
  1130. this.routes();
  1131. Backbone.history.start({
  1132. root: themes.data.settings.adminUrl,
  1133. pushState: true,
  1134. hashChange: false
  1135. });
  1136. },
  1137. routes: function() {
  1138. var self = this;
  1139. // Bind to our global thx object
  1140. // so that the object is available to sub-views
  1141. themes.router = new themes.Router();
  1142. // Handles theme details route event
  1143. themes.router.on( 'route:theme', function( slug ) {
  1144. self.view.view.expand( slug );
  1145. });
  1146. themes.router.on( 'route:themes', function() {
  1147. self.themes.doSearch( '' );
  1148. self.view.trigger( 'theme:close' );
  1149. });
  1150. // Handles search route event
  1151. themes.router.on( 'route:search', function() {
  1152. $( '.wp-filter-search' ).trigger( 'keyup' );
  1153. });
  1154. this.extraRoutes();
  1155. },
  1156. extraRoutes: function() {
  1157. return false;
  1158. }
  1159. };
  1160. // Extend the main Search view
  1161. themes.view.InstallerSearch = themes.view.Search.extend({
  1162. events: {
  1163. 'input': 'search',
  1164. 'keyup': 'search'
  1165. },
  1166. terms: '',
  1167. // Handles Ajax request for searching through themes in public repo
  1168. search: function( event ) {
  1169. // Tabbing or reverse tabbing into the search input shouldn't trigger a search
  1170. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1171. return;
  1172. }
  1173. this.collection = this.options.parent.view.collection;
  1174. // Clear on escape.
  1175. if ( event.type === 'keyup' && event.which === 27 ) {
  1176. event.target.value = '';
  1177. }
  1178. this.doSearch( event.target.value );
  1179. },
  1180. doSearch: _.debounce( function( value ) {
  1181. var request = {};
  1182. // Don't do anything if the search terms haven't changed.
  1183. if ( this.terms === value ) {
  1184. return;
  1185. }
  1186. // Updates terms with the value passed.
  1187. this.terms = value;
  1188. request.search = value;
  1189. // Intercept an [author] search.
  1190. //
  1191. // If input value starts with `author:` send a request
  1192. // for `author` instead of a regular `search`
  1193. if ( value.substring( 0, 7 ) === 'author:' ) {
  1194. request.search = '';
  1195. request.author = value.slice( 7 );
  1196. }
  1197. // Intercept a [tag] search.
  1198. //
  1199. // If input value starts with `tag:` send a request
  1200. // for `tag` instead of a regular `search`
  1201. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1202. request.search = '';
  1203. request.tag = [ value.slice( 4 ) ];
  1204. }
  1205. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1206. $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
  1207. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1208. // or searching the local cache
  1209. this.collection.query( request );
  1210. // Set route
  1211. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
  1212. }, 500 )
  1213. });
  1214. themes.view.Installer = themes.view.Appearance.extend({
  1215. el: '#wpbody-content .wrap',
  1216. // Register events for sorting and filters in theme-navigation
  1217. events: {
  1218. 'click .filter-links li > a': 'onSort',
  1219. 'click .theme-filter': 'onFilter',
  1220. 'click .drawer-toggle': 'moreFilters',
  1221. 'click .filter-drawer .apply-filters': 'applyFilters',
  1222. 'click .filter-group [type="checkbox"]': 'addFilter',
  1223. 'click .filter-drawer .clear-filters': 'clearFilters',
  1224. 'click .filtered-by': 'backToFilters',
  1225. 'click .favorites-form-submit' : 'saveUsername',
  1226. 'keyup #wporg-username-input': 'saveUsername'
  1227. },
  1228. // Initial render method
  1229. render: function() {
  1230. var self = this;
  1231. this.search();
  1232. this.uploader();
  1233. this.collection = new themes.Collection();
  1234. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1235. this.listenTo( this, 'theme:end', function() {
  1236. // Make sure we are not already loading
  1237. if ( self.collection.loadingThemes ) {
  1238. return;
  1239. }
  1240. // Set loadingThemes to true and bump page instance of currentQuery.
  1241. self.collection.loadingThemes = true;
  1242. self.collection.currentQuery.page++;
  1243. // Use currentQuery.page to build the themes request.
  1244. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1245. self.collection.query( self.collection.currentQuery.request );
  1246. });
  1247. this.listenTo( this.collection, 'query:success', function() {
  1248. $( 'body' ).removeClass( 'loading-content' );
  1249. $( '.theme-browser' ).find( 'div.error' ).remove();
  1250. });
  1251. this.listenTo( this.collection, 'query:fail', function() {
  1252. $( 'body' ).removeClass( 'loading-content' );
  1253. $( '.theme-browser' ).find( 'div.error' ).remove();
  1254. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
  1255. });
  1256. if ( this.view ) {
  1257. this.view.remove();
  1258. }
  1259. // Set ups the view and passes the section argument
  1260. this.view = new themes.view.Themes({
  1261. collection: this.collection,
  1262. parent: this
  1263. });
  1264. // Reset pagination every time the install view handler is run
  1265. this.page = 0;
  1266. // Render and append
  1267. this.$el.find( '.themes' ).remove();
  1268. this.view.render();
  1269. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1270. },
  1271. // Handles all the rendering of the public theme directory
  1272. browse: function( section ) {
  1273. // Create a new collection with the proper theme data
  1274. // for each section
  1275. this.collection.query( { browse: section } );
  1276. },
  1277. // Sorting navigation
  1278. onSort: function( event ) {
  1279. var $el = $( event.target ),
  1280. sort = $el.data( 'sort' );
  1281. event.preventDefault();
  1282. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1283. // Bail if this is already active
  1284. if ( $el.hasClass( this.activeClass ) ) {
  1285. return;
  1286. }
  1287. this.sort( sort );
  1288. // Trigger a router.naviagte update
  1289. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1290. },
  1291. sort: function( sort ) {
  1292. this.clearSearch();
  1293. $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
  1294. $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
  1295. if ( 'favorites' === sort ) {
  1296. $ ( 'body' ).addClass( 'show-favorites-form' );
  1297. } else {
  1298. $ ( 'body' ).removeClass( 'show-favorites-form' );
  1299. }
  1300. this.browse( sort );
  1301. },
  1302. // Filters and Tags
  1303. onFilter: function( event ) {
  1304. var request,
  1305. $el = $( event.target ),
  1306. filter = $el.data( 'filter' );
  1307. // Bail if this is already active
  1308. if ( $el.hasClass( this.activeClass ) ) {
  1309. return;
  1310. }
  1311. $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
  1312. $el.addClass( this.activeClass );
  1313. if ( ! filter ) {
  1314. return;
  1315. }
  1316. // Construct the filter request
  1317. // using the default values
  1318. filter = _.union( [ filter, this.filtersChecked() ] );
  1319. request = { tag: [ filter ] };
  1320. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1321. // or searching the local cache
  1322. this.collection.query( request );
  1323. },
  1324. // Clicking on a checkbox to add another filter to the request
  1325. addFilter: function() {
  1326. this.filtersChecked();
  1327. },
  1328. // Applying filters triggers a tag request
  1329. applyFilters: function( event ) {
  1330. var name,
  1331. tags = this.filtersChecked(),
  1332. request = { tag: tags },
  1333. filteringBy = $( '.filtered-by .tags' );
  1334. if ( event ) {
  1335. event.preventDefault();
  1336. }
  1337. $( 'body' ).addClass( 'filters-applied' );
  1338. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1339. filteringBy.empty();
  1340. _.each( tags, function( tag ) {
  1341. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1342. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1343. });
  1344. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1345. // or searching the local cache
  1346. this.collection.query( request );
  1347. },
  1348. // Save the user's WordPress.org username and get his favorite themes.
  1349. saveUsername: function ( event ) {
  1350. var username = $( '#wporg-username-input' ).val(),
  1351. nonce = $( '#wporg-username-nonce' ).val(),
  1352. request = { browse: 'favorites', user: username },
  1353. that = this;
  1354. if ( event ) {
  1355. event.preventDefault();
  1356. }
  1357. // save username on enter
  1358. if ( event.type === 'keyup' && event.which !== 13 ) {
  1359. return;
  1360. }
  1361. return wp.ajax.send( 'save-wporg-username', {
  1362. data: {
  1363. _wpnonce: nonce,
  1364. username: username
  1365. },
  1366. success: function () {
  1367. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1368. // or searching the local cache
  1369. that.collection.query( request );
  1370. }
  1371. } );
  1372. },
  1373. // Get the checked filters
  1374. // @return {array} of tags or false
  1375. filtersChecked: function() {
  1376. var items = $( '.filter-group' ).find( ':checkbox' ),
  1377. tags = [];
  1378. _.each( items.filter( ':checked' ), function( item ) {
  1379. tags.push( $( item ).prop( 'value' ) );
  1380. });
  1381. // When no filters are checked, restore initial state and return
  1382. if ( tags.length === 0 ) {
  1383. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1384. $( '.filter-drawer .clear-filters' ).hide();
  1385. $( 'body' ).removeClass( 'filters-applied' );
  1386. return false;
  1387. }
  1388. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1389. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1390. return tags;
  1391. },
  1392. activeClass: 'current',
  1393. // Overwrite search container class to append search
  1394. // in new location
  1395. searchContainer: $( '.wp-filter .search-form' ),
  1396. /*
  1397. * When users press the "Upload Theme" button, show the upload form in place.
  1398. */
  1399. uploader: function() {
  1400. var uploadViewToggle = $( '.upload-view-toggle' ),
  1401. $body = $( document.body );
  1402. uploadViewToggle.on( 'click', function() {
  1403. // Toggle the upload view.
  1404. $body.toggleClass( 'show-upload-view' );
  1405. // Toggle the `aria-expanded` button attribute.
  1406. uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
  1407. });
  1408. },
  1409. // Toggle the full filters navigation
  1410. moreFilters: function( event ) {
  1411. event.preventDefault();
  1412. if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
  1413. return this.backToFilters();
  1414. }
  1415. // If the filters section is opened and filters are checked
  1416. // run the relevant query collapsing to filtered-by state
  1417. if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
  1418. return this.addFilter();
  1419. }
  1420. this.clearSearch();
  1421. themes.router.navigate( themes.router.baseUrl( '' ) );
  1422. $( 'body' ).toggleClass( 'show-filters' );
  1423. },
  1424. // Clears all the checked filters
  1425. // @uses filtersChecked()
  1426. clearFilters: function( event ) {
  1427. var items = $( '.filter-group' ).find( ':checkbox' ),
  1428. self = this;
  1429. event.preventDefault();
  1430. _.each( items.filter( ':checked' ), function( item ) {
  1431. $( item ).prop( 'checked', false );
  1432. return self.filtersChecked();
  1433. });
  1434. },
  1435. backToFilters: function( event ) {
  1436. if ( event ) {
  1437. event.preventDefault();
  1438. }
  1439. $( 'body' ).removeClass( 'filters-applied' );
  1440. },
  1441. clearSearch: function() {
  1442. $( '#wp-filter-search-input').val( '' );
  1443. }
  1444. });
  1445. themes.InstallerRouter = Backbone.Router.extend({
  1446. routes: {
  1447. 'theme-install.php?theme=:slug': 'preview',
  1448. 'theme-install.php?browse=:sort': 'sort',
  1449. 'theme-install.php?search=:query': 'search',
  1450. 'theme-install.php': 'sort'
  1451. },
  1452. baseUrl: function( url ) {
  1453. return 'theme-install.php' + url;
  1454. },
  1455. themePath: '?theme=',
  1456. browsePath: '?browse=',
  1457. searchPath: '?search=',
  1458. search: function( query ) {
  1459. $( '.wp-filter-search' ).val( query );
  1460. },
  1461. navigate: function() {
  1462. if ( Backbone.history._hasPushState ) {
  1463. Backbone.Router.prototype.navigate.apply( this, arguments );
  1464. }
  1465. }
  1466. });
  1467. themes.RunInstaller = {
  1468. init: function() {
  1469. // Set up the view
  1470. // Passes the default 'section' as an option
  1471. this.view = new themes.view.Installer({
  1472. section: 'featured',
  1473. SearchView: themes.view.InstallerSearch
  1474. });
  1475. // Render results
  1476. this.render();
  1477. },
  1478. render: function() {
  1479. // Render results
  1480. this.view.render();
  1481. this.routes();
  1482. Backbone.history.start({
  1483. root: themes.data.settings.adminUrl,
  1484. pushState: true,
  1485. hashChange: false
  1486. });
  1487. },
  1488. routes: function() {
  1489. var self = this,
  1490. request = {};
  1491. // Bind to our global `wp.themes` object
  1492. // so that the router is available to sub-views
  1493. themes.router = new themes.InstallerRouter();
  1494. // Handles `theme` route event
  1495. // Queries the API for the passed theme slug
  1496. themes.router.on( 'route:preview', function( slug ) {
  1497. request.theme = slug;
  1498. self.view.collection.query( request );
  1499. self.view.collection.once( 'update', function() {
  1500. self.view.view.theme.preview();
  1501. });
  1502. });
  1503. // Handles sorting / browsing routes
  1504. // Also handles the root URL triggering a sort request
  1505. // for `featured`, the default view
  1506. themes.router.on( 'route:sort', function( sort ) {