PageRenderTime 61ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/js/theme.js

https://bitbucket.org/stephenharris/stephenharris
JavaScript | 1980 lines | 1223 code | 411 blank | 346 comment | 149 complexity | ecfb55ddd7b2f7340ee501195f636afb MD5 | raw file

Large files files are truncated, but you can click here to view the full 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. if ( ! this.model.get( 'hasPackage' ) ) {
  485. return;
  486. }
  487. event.preventDefault();
  488. wp.updates.maybeRequestFilesystemCredentials( event );
  489. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  490. _this.model.off( 'change', _this.render, _this );
  491. if ( _this.model.get( 'id' ) === response.slug ) {
  492. _this.model.set( {
  493. hasUpdate: false,
  494. version: response.newVersion
  495. } );
  496. }
  497. _this.model.on( 'change', _this.render, _this );
  498. } );
  499. wp.updates.updateTheme( {
  500. slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
  501. } );
  502. }
  503. });
  504. // Theme Details view
  505. // Set ups a modal overlay with the expanded theme data
  506. themes.view.Details = wp.Backbone.View.extend({
  507. // Wrap theme data on a div.theme element
  508. className: 'theme-overlay',
  509. events: {
  510. 'click': 'collapse',
  511. 'click .delete-theme': 'deleteTheme',
  512. 'click .left': 'previousTheme',
  513. 'click .right': 'nextTheme',
  514. 'click #update-theme': 'updateTheme'
  515. },
  516. // The HTML template for the theme overlay
  517. html: themes.template( 'theme-single' ),
  518. render: function() {
  519. var data = this.model.toJSON();
  520. this.$el.html( this.html( data ) );
  521. // Renders active theme styles
  522. this.activeTheme();
  523. // Set up navigation events
  524. this.navigation();
  525. // Checks screenshot size
  526. this.screenshotCheck( this.$el );
  527. // Contain "tabbing" inside the overlay
  528. this.containFocus( this.$el );
  529. },
  530. // Adds a class to the currently active theme
  531. // and to the overlay in detailed view mode
  532. activeTheme: function() {
  533. // Check the model has the active property
  534. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  535. },
  536. // Set initial focus and constrain tabbing within the theme browser modal.
  537. containFocus: function( $el ) {
  538. // Set initial focus on the primary action control.
  539. _.delay( function() {
  540. $( '.theme-wrap a.button-primary:visible' ).focus();
  541. }, 100 );
  542. // Constrain tabbing within the modal.
  543. $el.on( 'keydown.wp-themes', function( event ) {
  544. var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
  545. $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
  546. // Check for the Tab key.
  547. if ( 9 === event.which ) {
  548. if ( $firstFocusable[0] === event.target && event.shiftKey ) {
  549. $lastFocusable.focus();
  550. event.preventDefault();
  551. } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
  552. $firstFocusable.focus();
  553. event.preventDefault();
  554. }
  555. }
  556. });
  557. },
  558. // Single theme overlay screen
  559. // It's shown when clicking a theme
  560. collapse: function( event ) {
  561. var self = this,
  562. scroll;
  563. event = event || window.event;
  564. // Prevent collapsing detailed view when there is only one theme available
  565. if ( themes.data.themes.length === 1 ) {
  566. return;
  567. }
  568. // Detect if the click is inside the overlay
  569. // and don't close it unless the target was
  570. // the div.back button
  571. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
  572. // Add a temporary closing class while overlay fades out
  573. $( 'body' ).addClass( 'closing-overlay' );
  574. // With a quick fade out animation
  575. this.$el.fadeOut( 130, function() {
  576. // Clicking outside the modal box closes the overlay
  577. $( 'body' ).removeClass( 'closing-overlay' );
  578. // Handle event cleanup
  579. self.closeOverlay();
  580. // Get scroll position to avoid jumping to the top
  581. scroll = document.body.scrollTop;
  582. // Clean the url structure
  583. themes.router.navigate( themes.router.baseUrl( '' ) );
  584. // Restore scroll position
  585. document.body.scrollTop = scroll;
  586. // Return focus to the theme div
  587. if ( themes.focusedTheme ) {
  588. themes.focusedTheme.focus();
  589. }
  590. });
  591. }
  592. },
  593. // Handles .disabled classes for next/previous buttons
  594. navigation: function() {
  595. // Disable Left/Right when at the start or end of the collection
  596. if ( this.model.cid === this.model.collection.at(0).cid ) {
  597. this.$el.find( '.left' )
  598. .addClass( 'disabled' )
  599. .prop( 'disabled', true );
  600. }
  601. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  602. this.$el.find( '.right' )
  603. .addClass( 'disabled' )
  604. .prop( 'disabled', true );
  605. }
  606. },
  607. // Performs the actions to effectively close
  608. // the theme details overlay
  609. closeOverlay: function() {
  610. $( 'body' ).removeClass( 'modal-open' );
  611. this.remove();
  612. this.unbind();
  613. this.trigger( 'theme:collapse' );
  614. },
  615. updateTheme: function( event ) {
  616. var _this = this;
  617. event.preventDefault();
  618. wp.updates.maybeRequestFilesystemCredentials( event );
  619. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  620. if ( _this.model.get( 'id' ) === response.slug ) {
  621. _this.model.set( {
  622. hasUpdate: false,
  623. version: response.newVersion
  624. } );
  625. }
  626. _this.render();
  627. } );
  628. wp.updates.updateTheme( {
  629. slug: $( event.target ).data( 'slug' )
  630. } );
  631. },
  632. deleteTheme: function( event ) {
  633. var _this = this,
  634. _collection = _this.model.collection,
  635. _themes = themes;
  636. event.preventDefault();
  637. // Confirmation dialog for deleting a theme.
  638. if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
  639. return;
  640. }
  641. wp.updates.maybeRequestFilesystemCredentials( event );
  642. $( document ).one( 'wp-theme-delete-success', function( event, response ) {
  643. _this.$el.find( '.close' ).trigger( 'click' );
  644. $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
  645. $( this ).remove();
  646. _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
  647. $( '.wp-filter-search' ).val( '' );
  648. _collection.doSearch( '' );
  649. _collection.remove( _this.model );
  650. _collection.trigger( 'themes:update' );
  651. } );
  652. } );
  653. wp.updates.deleteTheme( {
  654. slug: this.model.get( 'id' )
  655. } );
  656. },
  657. nextTheme: function() {
  658. var self = this;
  659. self.trigger( 'theme:next', self.model.cid );
  660. return false;
  661. },
  662. previousTheme: function() {
  663. var self = this;
  664. self.trigger( 'theme:previous', self.model.cid );
  665. return false;
  666. },
  667. // Checks if the theme screenshot is the old 300px width version
  668. // and adds a corresponding class if it's true
  669. screenshotCheck: function( el ) {
  670. var screenshot, image;
  671. screenshot = el.find( '.screenshot img' );
  672. image = new Image();
  673. image.src = screenshot.attr( 'src' );
  674. // Width check
  675. if ( image.width && image.width <= 300 ) {
  676. el.addClass( 'small-screenshot' );
  677. }
  678. }
  679. });
  680. // Theme Preview view
  681. // Set ups a modal overlay with the expanded theme data
  682. themes.view.Preview = themes.view.Details.extend({
  683. className: 'wp-full-overlay expanded',
  684. el: '.theme-install-overlay',
  685. events: {
  686. 'click .close-full-overlay': 'close',
  687. 'click .collapse-sidebar': 'collapse',
  688. 'click .devices button': 'previewDevice',
  689. 'click .previous-theme': 'previousTheme',
  690. 'click .next-theme': 'nextTheme',
  691. 'keyup': 'keyEvent',
  692. 'click .theme-install': 'installTheme'
  693. },
  694. // The HTML template for the theme preview
  695. html: themes.template( 'theme-preview' ),
  696. render: function() {
  697. var self = this,
  698. currentPreviewDevice,
  699. data = this.model.toJSON(),
  700. $body = $( document.body );
  701. $body.attr( 'aria-busy', 'true' );
  702. this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
  703. currentPreviewDevice = this.$el.data( 'current-preview-device' );
  704. if ( currentPreviewDevice ) {
  705. self.tooglePreviewDeviceButtons( currentPreviewDevice );
  706. }
  707. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
  708. this.$el.fadeIn( 200, function() {
  709. $body.addClass( 'theme-installer-active full-overlay-active' );
  710. });
  711. this.$el.find( 'iframe' ).one( 'load', function() {
  712. self.iframeLoaded();
  713. });
  714. },
  715. iframeLoaded: function() {
  716. this.$el.addClass( 'iframe-ready' );
  717. $( document.body ).attr( 'aria-busy', 'false' );
  718. },
  719. close: function() {
  720. this.$el.fadeOut( 200, function() {
  721. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  722. // Return focus to the theme div
  723. if ( themes.focusedTheme ) {
  724. themes.focusedTheme.focus();
  725. }
  726. }).removeClass( 'iframe-ready' );
  727. themes.router.navigate( themes.router.baseUrl( '' ) );
  728. this.trigger( 'preview:close' );
  729. this.undelegateEvents();
  730. this.unbind();
  731. return false;
  732. },
  733. collapse: function( event ) {
  734. var $button = $( event.currentTarget );
  735. if ( 'true' === $button.attr( 'aria-expanded' ) ) {
  736. $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
  737. } else {
  738. $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
  739. }
  740. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  741. return false;
  742. },
  743. previewDevice: function( event ) {
  744. var device = $( event.currentTarget ).data( 'device' );
  745. this.$el
  746. .removeClass( 'preview-desktop preview-tablet preview-mobile' )
  747. .addClass( 'preview-' + device )
  748. .data( 'current-preview-device', device );
  749. this.tooglePreviewDeviceButtons( device );
  750. },
  751. tooglePreviewDeviceButtons: function( newDevice ) {
  752. var $devices = $( '.wp-full-overlay-footer .devices' );
  753. $devices.find( 'button' )
  754. .removeClass( 'active' )
  755. .attr( 'aria-pressed', false );
  756. $devices.find( 'button.preview-' + newDevice )
  757. .addClass( 'active' )
  758. .attr( 'aria-pressed', true );
  759. },
  760. keyEvent: function( event ) {
  761. // The escape key closes the preview
  762. if ( event.keyCode === 27 ) {
  763. this.undelegateEvents();
  764. this.close();
  765. }
  766. // The right arrow key, next theme
  767. if ( event.keyCode === 39 ) {
  768. _.once( this.nextTheme() );
  769. }
  770. // The left arrow key, previous theme
  771. if ( event.keyCode === 37 ) {
  772. this.previousTheme();
  773. }
  774. },
  775. installTheme: function( event ) {
  776. var _this = this,
  777. $target = $( event.target );
  778. event.preventDefault();
  779. if ( $target.hasClass( 'disabled' ) ) {
  780. return;
  781. }
  782. wp.updates.maybeRequestFilesystemCredentials( event );
  783. $( document ).on( 'wp-theme-install-success', function() {
  784. _this.model.set( { 'installed': true } );
  785. } );
  786. wp.updates.installTheme( {
  787. slug: $target.data( 'slug' )
  788. } );
  789. }
  790. });
  791. // Controls the rendering of div.themes,
  792. // a wrapper that will hold all the theme elements
  793. themes.view.Themes = wp.Backbone.View.extend({
  794. className: 'themes wp-clearfix',
  795. $overlay: $( 'div.theme-overlay' ),
  796. // Number to keep track of scroll position
  797. // while in theme-overlay mode
  798. index: 0,
  799. // The theme count element
  800. count: $( '.wrap .theme-count' ),
  801. // The live themes count
  802. liveThemeCount: 0,
  803. initialize: function( options ) {
  804. var self = this;
  805. // Set up parent
  806. this.parent = options.parent;
  807. // Set current view to [grid]
  808. this.setView( 'grid' );
  809. // Move the active theme to the beginning of the collection
  810. self.currentTheme();
  811. // When the collection is updated by user input...
  812. this.listenTo( self.collection, 'themes:update', function() {
  813. self.parent.page = 0;
  814. self.currentTheme();
  815. self.render( this );
  816. } );
  817. // Update theme count to full result set when available.
  818. this.listenTo( self.collection, 'query:success', function( count ) {
  819. if ( _.isNumber( count ) ) {
  820. self.count.text( count );
  821. self.announceSearchResults( count );
  822. } else {
  823. self.count.text( self.collection.length );
  824. self.announceSearchResults( self.collection.length );
  825. }
  826. });
  827. this.listenTo( self.collection, 'query:empty', function() {
  828. $( 'body' ).addClass( 'no-results' );
  829. });
  830. this.listenTo( this.parent, 'theme:scroll', function() {
  831. self.renderThemes( self.parent.page );
  832. });
  833. this.listenTo( this.parent, 'theme:close', function() {
  834. if ( self.overlay ) {
  835. self.overlay.closeOverlay();
  836. }
  837. } );
  838. // Bind keyboard events.
  839. $( 'body' ).on( 'keyup', function( event ) {
  840. if ( ! self.overlay ) {
  841. return;
  842. }
  843. // Bail if the filesystem credentials dialog is shown.
  844. if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
  845. return;
  846. }
  847. // Pressing the right arrow key fires a theme:next event
  848. if ( event.keyCode === 39 ) {
  849. self.overlay.nextTheme();
  850. }
  851. // Pressing the left arrow key fires a theme:previous event
  852. if ( event.keyCode === 37 ) {
  853. self.overlay.previousTheme();
  854. }
  855. // Pressing the escape key fires a theme:collapse event
  856. if ( event.keyCode === 27 ) {
  857. self.overlay.collapse( event );
  858. }
  859. });
  860. },
  861. // Manages rendering of theme pages
  862. // and keeping theme count in sync
  863. render: function() {
  864. // Clear the DOM, please
  865. this.$el.empty();
  866. // If the user doesn't have switch capabilities
  867. // or there is only one theme in the collection
  868. // render the detailed view of the active theme
  869. if ( themes.data.themes.length === 1 ) {
  870. // Constructs the view
  871. this.singleTheme = new themes.view.Details({
  872. model: this.collection.models[0]
  873. });
  874. // Render and apply a 'single-theme' class to our container
  875. this.singleTheme.render();
  876. this.$el.addClass( 'single-theme' );
  877. this.$el.append( this.singleTheme.el );
  878. }
  879. // Generate the themes
  880. // Using page instance
  881. // While checking the collection has items
  882. if ( this.options.collection.size() > 0 ) {
  883. this.renderThemes( this.parent.page );
  884. }
  885. // Display a live theme count for the collection
  886. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  887. this.count.text( this.liveThemeCount );
  888. /*
  889. * In the theme installer the themes count is already announced
  890. * because `announceSearchResults` is called on `query:success`.
  891. */
  892. if ( ! themes.isInstall ) {
  893. this.announceSearchResults( this.liveThemeCount );
  894. }
  895. },
  896. // Iterates through each instance of the collection
  897. // and renders each theme module
  898. renderThemes: function( page ) {
  899. var self = this;
  900. self.instance = self.collection.paginate( page );
  901. // If we have no more themes bail
  902. if ( self.instance.size() === 0 ) {
  903. // Fire a no-more-themes event.
  904. this.parent.trigger( 'theme:end' );
  905. return;
  906. }
  907. // Make sure the add-new stays at the end
  908. if ( ! themes.isInstall && page >= 1 ) {
  909. $( '.add-new-theme' ).remove();
  910. }
  911. // Loop through the themes and setup each theme view
  912. self.instance.each( function( theme ) {
  913. self.theme = new themes.view.Theme({
  914. model: theme,
  915. parent: self
  916. });
  917. // Render the views...
  918. self.theme.render();
  919. // and append them to div.themes
  920. self.$el.append( self.theme.el );
  921. // Binds to theme:expand to show the modal box
  922. // with the theme details
  923. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  924. });
  925. // 'Add new theme' element shown at the end of the grid
  926. if ( ! themes.isInstall && themes.data.settings.canInstall ) {
  927. 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>' );
  928. }
  929. this.parent.page++;
  930. },
  931. // Grabs current theme and puts it at the beginning of the collection
  932. currentTheme: function() {
  933. var self = this,
  934. current;
  935. current = self.collection.findWhere({ active: true });
  936. // Move the active theme to the beginning of the collection
  937. if ( current ) {
  938. self.collection.remove( current );
  939. self.collection.add( current, { at:0 } );
  940. }
  941. },
  942. // Sets current view
  943. setView: function( view ) {
  944. return view;
  945. },
  946. // Renders the overlay with the ThemeDetails view
  947. // Uses the current model data
  948. expand: function( id ) {
  949. var self = this, $card, $modal;
  950. // Set the current theme model
  951. this.model = self.collection.get( id );
  952. // Trigger a route update for the current model
  953. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  954. // Sets this.view to 'detail'
  955. this.setView( 'detail' );
  956. $( 'body' ).addClass( 'modal-open' );
  957. // Set up the theme details view
  958. this.overlay = new themes.view.Details({
  959. model: self.model
  960. });
  961. this.overlay.render();
  962. if ( this.model.get( 'hasUpdate' ) ) {
  963. $card = $( '[data-slug="' + this.model.id + '"]' );
  964. $modal = $( this.overlay.el );
  965. if ( $card.find( '.updating-message' ).length ) {
  966. $modal.find( '.notice-warning h3' ).remove();
  967. $modal.find( '.notice-warning' )
  968. .removeClass( 'notice-large' )
  969. .addClass( 'updating-message' )
  970. .find( 'p' ).text( wp.updates.l10n.updating );
  971. } else if ( $card.find( '.notice-error' ).length ) {
  972. $modal.find( '.notice-warning' ).remove();
  973. }
  974. }
  975. this.$overlay.html( this.overlay.el );
  976. // Bind to theme:next and theme:previous
  977. // triggered by the arrow keys
  978. //
  979. // Keep track of the current model so we
  980. // can infer an index position
  981. this.listenTo( this.overlay, 'theme:next', function() {
  982. // Renders the next theme on the overlay
  983. self.next( [ self.model.cid ] );
  984. })
  985. .listenTo( this.overlay, 'theme:previous', function() {
  986. // Renders the previous theme on the overlay
  987. self.previous( [ self.model.cid ] );
  988. });
  989. },
  990. // This method renders the next theme on the overlay modal
  991. // based on the current position in the collection
  992. // @params [model cid]
  993. next: function( args ) {
  994. var self = this,
  995. model, nextModel;
  996. // Get the current theme
  997. model = self.collection.get( args[0] );
  998. // Find the next model within the collection
  999. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  1000. // Sanity check which also serves as a boundary test
  1001. if ( nextModel !== undefined ) {
  1002. // We have a new theme...
  1003. // Close the overlay
  1004. this.overlay.closeOverlay();
  1005. // Trigger a route update for the current model
  1006. self.theme.trigger( 'theme:expand', nextModel.cid );
  1007. }
  1008. },
  1009. // This method renders the previous theme on the overlay modal
  1010. // based on the current position in the collection
  1011. // @params [model cid]
  1012. previous: function( args ) {
  1013. var self = this,
  1014. model, previousModel;
  1015. // Get the current theme
  1016. model = self.collection.get( args[0] );
  1017. // Find the previous model within the collection
  1018. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  1019. if ( previousModel !== undefined ) {
  1020. // We have a new theme...
  1021. // Close the overlay
  1022. this.overlay.closeOverlay();
  1023. // Trigger a route update for the current model
  1024. self.theme.trigger( 'theme:expand', previousModel.cid );
  1025. }
  1026. },
  1027. // Dispatch audible search results feedback message
  1028. announceSearchResults: function( count ) {
  1029. if ( 0 === count ) {
  1030. wp.a11y.speak( l10n.noThemesFound );
  1031. } else {
  1032. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  1033. }
  1034. }
  1035. });
  1036. // Search input view controller.
  1037. themes.view.Search = wp.Backbone.View.extend({
  1038. tagName: 'input',
  1039. className: 'wp-filter-search',
  1040. id: 'wp-filter-search-input',
  1041. searching: false,
  1042. attributes: {
  1043. placeholder: l10n.searchPlaceholder,
  1044. type: 'search',
  1045. 'aria-describedby': 'live-search-desc'
  1046. },
  1047. events: {
  1048. 'input': 'search',
  1049. 'keyup': 'search',
  1050. 'blur': 'pushState'
  1051. },
  1052. initialize: function( options ) {
  1053. this.parent = options.parent;
  1054. this.listenTo( this.parent, 'theme:close', function() {
  1055. this.searching = false;
  1056. } );
  1057. },
  1058. search: function( event ) {
  1059. // Clear on escape.
  1060. if ( event.type === 'keyup' && event.which === 27 ) {
  1061. event.target.value = '';
  1062. }
  1063. /**
  1064. * Since doSearch is debounced, it will only run when user input comes to a rest
  1065. */
  1066. this.doSearch( event );
  1067. },
  1068. // Runs a search on the theme collection.
  1069. doSearch: _.debounce( function( event ) {
  1070. var options = {};
  1071. this.collection.doSearch( event.target.value );
  1072. // if search is initiated and key is not return
  1073. if ( this.searching && event.which !== 13 ) {
  1074. options.replace = true;
  1075. } else {
  1076. this.searching = true;
  1077. }
  1078. // Update the URL hash
  1079. if ( event.target.value ) {
  1080. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  1081. } else {
  1082. themes.router.navigate( themes.router.baseUrl( '' ) );
  1083. }
  1084. }, 500 ),
  1085. pushState: function( event ) {
  1086. var url = themes.router.baseUrl( '' );
  1087. if ( event.target.value ) {
  1088. url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
  1089. }
  1090. this.searching = false;
  1091. themes.router.navigate( url );
  1092. }
  1093. });
  1094. // Sets up the routes events for relevant url queries
  1095. // Listens to [theme] and [search] params
  1096. themes.Router = Backbone.Router.extend({
  1097. routes: {
  1098. 'themes.php?theme=:slug': 'theme',
  1099. 'themes.php?search=:query': 'search',
  1100. 'themes.php?s=:query': 'search',
  1101. 'themes.php': 'themes',
  1102. '': 'themes'
  1103. },
  1104. baseUrl: function( url ) {
  1105. return 'themes.php' + url;
  1106. },
  1107. themePath: '?theme=',
  1108. searchPath: '?search=',
  1109. search: function( query ) {
  1110. $( '.wp-filter-search' ).val( query );
  1111. },
  1112. themes: function() {
  1113. $( '.wp-filter-search' ).val( '' );
  1114. },
  1115. navigate: function() {
  1116. if ( Backbone.history._hasPushState ) {
  1117. Backbone.Router.prototype.navigate.apply( this, arguments );
  1118. }
  1119. }
  1120. });
  1121. // Execute and setup the application
  1122. themes.Run = {
  1123. init: function() {
  1124. // Initializes the blog's theme library view
  1125. // Create a new collection with data
  1126. this.themes = new themes.Collection( themes.data.themes );
  1127. // Set up the view
  1128. this.view = new themes.view.Appearance({
  1129. collection: this.themes
  1130. });
  1131. this.render();
  1132. },
  1133. render: function() {
  1134. // Render results
  1135. this.view.render();
  1136. this.routes();
  1137. Backbone.history.start({
  1138. root: themes.data.settings.adminUrl,
  1139. pushState: true,
  1140. hashChange: false
  1141. });
  1142. },
  1143. routes: function() {
  1144. var self = this;
  1145. // Bind to our global thx object
  1146. // so that the object is available to sub-views
  1147. themes.router = new themes.Router();
  1148. // Handles theme details route event
  1149. themes.router.on( 'route:theme', function( slug ) {
  1150. self.view.view.expand( slug );
  1151. });
  1152. themes.router.on( 'route:themes', function() {
  1153. self.themes.doSearch( '' );
  1154. self.view.trigger( 'theme:close' );
  1155. });
  1156. // Handles search route event
  1157. themes.router.on( 'route:search', function() {
  1158. $( '.wp-filter-search' ).trigger( 'keyup' );
  1159. });
  1160. this.extraRoutes();
  1161. },
  1162. extraRoutes: function() {
  1163. return false;
  1164. }
  1165. };
  1166. // Extend the main Search view
  1167. themes.view.InstallerSearch = themes.view.Search.extend({
  1168. events: {
  1169. 'input': 'search',
  1170. 'keyup': 'search'
  1171. },
  1172. terms: '',
  1173. // Handles Ajax request for searching through themes in public repo
  1174. search: function( event ) {
  1175. // Tabbing or reverse tabbing into the search input shouldn't trigger a search
  1176. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1177. return;
  1178. }
  1179. this.collection = this.options.parent.view.collection;
  1180. // Clear on escape.
  1181. if ( event.type === 'keyup' && event.which === 27 ) {
  1182. event.target.value = '';
  1183. }
  1184. this.doSearch( event.target.value );
  1185. },
  1186. doSearch: _.debounce( function( value ) {
  1187. var request = {};
  1188. // Don't do anything if the search terms haven't changed.
  1189. if ( this.terms === value ) {
  1190. return;
  1191. }
  1192. // Updates terms with the value passed.
  1193. this.terms = value;
  1194. request.search = value;
  1195. // Intercept an [author] search.
  1196. //
  1197. // If input value starts with `author:` send a request
  1198. // for `author` instead of a regular `search`
  1199. if ( value.substring( 0, 7 ) === 'author:' ) {
  1200. request.search = '';
  1201. request.author = value.slice( 7 );
  1202. }
  1203. // Intercept a [tag] search.
  1204. //
  1205. // If input value starts with `tag:` send a request
  1206. // for `tag` instead of a regular `search`
  1207. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1208. request.search = '';
  1209. request.tag = [ value.slice( 4 ) ];
  1210. }
  1211. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1212. $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
  1213. $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
  1214. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1215. // or searching the local cache
  1216. this.collection.query( request );
  1217. // Set route
  1218. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
  1219. }, 500 )
  1220. });
  1221. themes.view.Installer = themes.view.Appearance.extend({
  1222. el: '#wpbody-content .wrap',
  1223. // Register events for sorting and filters in theme-navigation
  1224. events: {
  1225. 'click .filter-links li > a': 'onSort',
  1226. 'click .theme-filter': 'onFilter',
  1227. 'click .drawer-toggle': 'moreFilters',
  1228. 'click .filter-drawer .apply-filters': 'applyFilters',
  1229. 'click .filter-group [type="checkbox"]': 'addFilter',
  1230. 'click .filter-drawer .clear-filters': 'clearFilters',
  1231. 'click .edit-filters': 'backToFilters',
  1232. 'click .favorites-form-submit' : 'saveUsername',
  1233. 'keyup #wporg-username-input': 'saveUsername'
  1234. },
  1235. // Initial render method
  1236. render: function() {
  1237. var self = this;
  1238. this.search();
  1239. this.uploader();
  1240. this.collection = new themes.Collection();
  1241. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1242. this.listenTo( this, 'theme:end', function() {
  1243. // Make sure we are not already loading
  1244. if ( self.collection.loadingThemes ) {
  1245. return;
  1246. }
  1247. // Set loadingThemes to true and bump page instance of currentQuery.
  1248. self.collection.loadingThemes = true;
  1249. self.collection.currentQuery.page++;
  1250. // Use currentQuery.page to build the themes request.
  1251. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1252. self.collection.query( self.collection.currentQuery.request );
  1253. });
  1254. this.listenTo( this.collection, 'query:success', function() {
  1255. $( 'body' ).removeClass( 'loading-content' );
  1256. $( '.theme-browser' ).find( 'div.error' ).remove();
  1257. });
  1258. this.listenTo( this.collection, 'query:fail', function() {
  1259. $( 'body' ).removeClass( 'loading-content' );
  1260. $( '.theme-browser' ).find( 'div.error' ).remove();
  1261. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
  1262. });
  1263. if ( this.view ) {
  1264. this.view.remove();
  1265. }
  1266. // Set ups the view and passes the section argument
  1267. this.view = new themes.view.Themes({
  1268. collection: this.collection,
  1269. parent: this
  1270. });
  1271. // Reset pagination every time the install view handler is run
  1272. this.page = 0;
  1273. // Render and append
  1274. this.$el.find( '.themes' ).remove();
  1275. this.view.render();
  1276. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1277. },
  1278. // Handles all the rendering of the public theme directory
  1279. browse: function( section ) {
  1280. // Create a new collection with the proper theme data
  1281. // for each section
  1282. this.collection.query( { browse: section } );
  1283. },
  1284. // Sorting navigation
  1285. onSort: function( event ) {
  1286. var $el = $( event.target ),
  1287. sort = $el.data( 'sort' );
  1288. event.preventDefault();
  1289. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1290. $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
  1291. // Bail if this is already active
  1292. if ( $el.hasClass( this.activeClass ) ) {
  1293. return;
  1294. }
  1295. this.sort( sort );
  1296. // Trigger a router.naviagte update
  1297. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1298. },
  1299. sort: function( sort ) {
  1300. this.clearSearch();
  1301. $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
  1302. $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
  1303. if ( 'favorites' === sort ) {
  1304. $( 'body' ).addClass( 'show-favorites-form' );
  1305. } else {
  1306. $( 'body' ).removeClass( 'show-favorites-form' );
  1307. }
  1308. this.browse( sort );
  1309. },
  1310. // Filters and Tags
  1311. onFilter: function( event ) {
  1312. var request,
  1313. $el = $( event.target ),
  1314. filter = $el.data( 'filter' );
  1315. // Bail if this is already active
  1316. if ( $el.hasClass( this.activeClass ) ) {
  1317. return;
  1318. }
  1319. $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
  1320. $el.addClass( this.activeClass );
  1321. if ( ! filter ) {
  1322. return;
  1323. }
  1324. // Construct the filter request
  1325. // using the default values
  1326. filter = _.union( [ filter, this.filtersChecked() ] );
  1327. request = { tag: [ filter ] };
  1328. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1329. // or searching the local cache
  1330. this.collection.query( request );
  1331. },
  1332. // Clicking on a checkbox to add another filter to the request
  1333. addFilter: function() {
  1334. this.filtersChecked();
  1335. },
  1336. // Applying filters triggers a tag request
  1337. applyFilters: function( event ) {
  1338. var name,
  1339. tags = this.filtersChecked(),
  1340. request = { tag: tags },
  1341. filteringBy = $( '.filtered-by .tags' );
  1342. if ( event ) {
  1343. event.preventDefault();
  1344. }
  1345. if ( ! tags ) {
  1346. wp.a11y.speak( l10n.selectFeatureFilter );
  1347. return;
  1348. }
  1349. $( 'body' ).addClass( 'filters-applied' );
  1350. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1351. filteringBy.empty();
  1352. _.each( tags, function( tag ) {
  1353. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1354. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1355. });
  1356. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1357. // or searching the local cache
  1358. this.collection.query( request );
  1359. },
  1360. // Save the user's WordPress.org username and get his favorite themes.
  1361. saveUsername: function ( event ) {
  1362. var username = $( '#wporg-username-input' ).val(),
  1363. nonce = $( '#wporg-username-nonce' ).val(),
  1364. request = { browse: 'favorites', user: username },
  1365. that = this;
  1366. if ( event ) {
  1367. event.preventDefault();
  1368. }
  1369. // save username on enter
  1370. if ( event.type === 'keyup' && event.which !== 13 ) {
  1371. return;
  1372. }
  1373. return wp.ajax.send( 'save-wporg-username', {
  1374. data: {
  1375. _wpnonce: nonce,
  1376. username: username
  1377. },
  1378. success: function () {
  1379. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1380. // or searching the local cache
  1381. that.collection.query( request );
  1382. }
  1383. } );
  1384. },
  1385. // Get the checked filters
  1386. // @return {array} of tags or false
  1387. filtersChecked: function() {
  1388. var items = $( '.filter-group' ).find( ':checkbox' ),
  1389. tags = [];
  1390. _.each( items.filter( ':checked' ), function( item ) {
  1391. tags.push( $( item ).prop( 'value' ) );
  1392. });
  1393. // When no filters are checked, restore initial state and return
  1394. if ( tags.length === 0 ) {
  1395. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1396. $( '.filter-drawer .clear-filters' ).hide();
  1397. $( 'body' ).removeClass( 'filters-applied' );
  1398. return false;
  1399. }
  1400. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1401. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1402. return tags;
  1403. },
  1404. activeClass: 'current',
  1405. // Overwrite search container class to append search
  1406. // in new location
  1407. searchContainer: $( '.wp-filter .search-form' ),
  1408. /*
  1409. * When users press the "Upload Theme" button, show the upload form in place.
  1410. */
  1411. uploader: function() {
  1412. var uploadViewToggle = $( '.upload-view-toggle' ),
  1413. $body = $( document.body );
  1414. uploadViewToggle.on( 'click', function() {
  1415. // Toggle the upload view.
  1416. $body.toggleClass( 'show-upload-view' );
  1417. // Toggle the `aria-expanded` button attribute.
  1418. uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
  1419. });
  1420. },
  1421. // Toggle the full filters navigation
  1422. moreFilters: function( event ) {
  1423. var $body = $( 'body' ),
  1424. $toggleButton = $( '.drawer-toggle' );
  1425. event.preventDefault();
  1426. if ( $body.hasClass( 'filters-applied' ) ) {
  1427. return this.backToFilters();
  1428. }
  1429. this.clearSearch();
  1430. themes.router.navigate( themes.router.baseUrl( '' ) );
  1431. // Toggle the feature filters view.
  1432. $body.toggleClass( 'show-filters' );
  1433. // Toggle the `aria-expanded` button attribute.
  1434. $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
  1435. },
  1436. // Clears all the checked filters
  1437. // @uses filtersChecked()
  1438. clearFilters: function( event ) {
  1439. var items = $( '.filter-group' ).find( ':checkbox' ),
  1440. self = this;
  1441. event.preventDefault();
  1442. _.each( items.filter( ':checked' ), function( item ) {
  1443. $( item ).prop( 'checked', false );
  1444. return self.filtersChecked();
  1445. });
  1446. },
  1447. backToFilters: function( event ) {
  1448. if ( event ) {
  1449. event.preventDefault();
  1450. }
  1451. $( 'body' ).removeClass( 'filters-applied' );
  1452. },
  1453. clearSearch: function() {
  1454. $( '#wp-filter-search-input').val( '' );
  1455. }
  1456. });
  1457. themes.InstallerRouter = Backbone.Router.extend({
  1458. routes: {
  1459. 'theme-install.php?theme=:slug': 'preview',
  1460. 'theme-install.php?browse=:sort': 'sort',
  1461. 'theme-install.php?search=:query': 'search',
  1462. 'theme-install.php': 'sort'
  1463. },
  1464. baseUrl: function( url ) {
  1465. return 'theme-install.php' + url;
  1466. },
  1467. themePath: '?theme=',
  1468. browsePath: '?browse=',
  1469. searchPath: '?search=',
  1470. search: function( query ) {
  1471. $( '.wp-filter-search' ).val( query );
  1472. },
  1473. navigate: function() {
  1474. if ( Backbone.history._hasPushState ) {
  1475. Backbone.Router.prototype.navigate.apply( this, arguments );
  1476. }
  1477. }
  1478. });
  1479. themes.RunInstaller = {
  1480. init: function() {
  1481. // Set up the view
  1482. // Passes the default 'section' as an option
  1483. this.view = new themes.view.Installer({
  1484. section: 'featured',
  1485. SearchView: themes.view.InstallerSearch
  1486. });
  1487. // Render results
  1488. this.render();
  1489. },
  1490. render: function() {
  1491. // Render results
  1492. this.view.render();
  1493. this.routes();
  1494. Backbone.history.start({
  1495. root: themes.data.settings.adminUrl,
  1496. pushState: true,
  1497. hashChange: false
  1498. });
  1499. },
  1500. routes: function() {
  1501. var self = this,
  1502. request = {};
  1503. // Bind to our global `wp.themes` object
  1504. // so that the router is available to sub-views
  1505. themes.router = new themes.InstallerRouter();
  1506. // Handles `theme` route event
  1507. // Queries the API for the passed theme slug
  1508. themes.router.on( 'route:preview', function( slug ) {
  1509. request.theme = slug;
  1510. sel

Large files files are truncated, but you can click here to view the full file