PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/js/theme.js

http://github.com/wordpress/wordpress
JavaScript | 2087 lines | 1276 code | 429 blank | 382 comment | 157 complexity | 0c2e021310bbd9bf031b4d3b42fe0377 MD5 | raw file
Possible License(s): 0BSD

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

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

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